opt-cc/opt-cc-api/public/vendor.bundle.js

72947 lines
2.5 MiB

webpackJsonp([4,5],[
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var root_1 = __webpack_require__(16);
var toSubscriber_1 = __webpack_require__(327);
var observable_1 = __webpack_require__(80);
/**
* A representation of any set of values over any amount of time. This the most basic building block
* of RxJS.
*
* @class Observable<T>
*/
var Observable = (function () {
/**
* @constructor
* @param {Function} subscribe the function that is called when the Observable is
* initially subscribed to. This function is given a Subscriber, to which new values
* can be `next`ed, or an `error` method can be called to raise an error, or
* `complete` can be called to notify of a successful completion.
*/
function Observable(subscribe) {
this._isScalar = false;
if (subscribe) {
this._subscribe = subscribe;
}
}
/**
* Creates a new Observable, with this Observable as the source, and the passed
* operator defined as the new observable's operator.
* @method lift
* @param {Operator} operator the operator defining the operation to take on the observable
* @return {Observable} a new observable with the Operator applied
*/
Observable.prototype.lift = function (operator) {
var observable = new Observable();
observable.source = this;
observable.operator = operator;
return observable;
};
Observable.prototype.subscribe = function (observerOrNext, error, complete) {
var operator = this.operator;
var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
if (operator) {
operator.call(sink, this.source);
}
else {
sink.add(this._trySubscribe(sink));
}
if (sink.syncErrorThrowable) {
sink.syncErrorThrowable = false;
if (sink.syncErrorThrown) {
throw sink.syncErrorValue;
}
}
return sink;
};
Observable.prototype._trySubscribe = function (sink) {
try {
return this._subscribe(sink);
}
catch (err) {
sink.syncErrorThrown = true;
sink.syncErrorValue = err;
sink.error(err);
}
};
/**
* @method forEach
* @param {Function} next a handler for each value emitted by the observable
* @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
* @return {Promise} a promise that either resolves on observable completion or
* rejects with the handled error
*/
Observable.prototype.forEach = function (next, PromiseCtor) {
var _this = this;
if (!PromiseCtor) {
if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
PromiseCtor = root_1.root.Rx.config.Promise;
}
else if (root_1.root.Promise) {
PromiseCtor = root_1.root.Promise;
}
}
if (!PromiseCtor) {
throw new Error('no Promise impl found');
}
return new PromiseCtor(function (resolve, reject) {
// Must be declared in a separate statement to avoid a RefernceError when
// accessing subscription below in the closure due to Temporal Dead Zone.
var subscription;
subscription = _this.subscribe(function (value) {
if (subscription) {
// if there is a subscription, then we can surmise
// the next handling is asynchronous. Any errors thrown
// need to be rejected explicitly and unsubscribe must be
// called manually
try {
next(value);
}
catch (err) {
reject(err);
subscription.unsubscribe();
}
}
else {
// if there is NO subscription, then we're getting a nexted
// value synchronously during subscription. We can just call it.
// If it errors, Observable's `subscribe` will ensure the
// unsubscription logic is called, then synchronously rethrow the error.
// After that, Promise will trap the error and send it
// down the rejection path.
next(value);
}
}, reject, resolve);
});
};
Observable.prototype._subscribe = function (subscriber) {
return this.source.subscribe(subscriber);
};
/**
* An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
* @method Symbol.observable
* @return {Observable} this instance of the observable
*/
Observable.prototype[observable_1.observable] = function () {
return this;
};
// HACK: Since TypeScript inherits static properties too, we have to
// fight against TypeScript here so Subject can have a different static create signature
/**
* Creates a new cold Observable by calling the Observable constructor
* @static true
* @owner Observable
* @method create
* @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
* @return {Observable} a new cold observable
*/
Observable.create = function (subscribe) {
return new Observable(subscribe);
};
return Observable;
}());
exports.Observable = Observable;
//# sourceMappingURL=Observable.js.map
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_rxjs_Observable__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_rxjs_Observable___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_rxjs_Observable__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_rxjs_observable_merge__ = __webpack_require__(109);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_rxjs_observable_merge___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_rxjs_observable_merge__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_rxjs_operator_share__ = __webpack_require__(319);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_rxjs_operator_share___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_rxjs_operator_share__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_rxjs_Subject__ = __webpack_require__(25);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_rxjs_Subject___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_rxjs_Subject__);
/* unused harmony export Class */
/* unused harmony export createPlatform */
/* unused harmony export assertPlatform */
/* unused harmony export destroyPlatform */
/* unused harmony export getPlatform */
/* unused harmony export PlatformRef */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "y", function() { return ApplicationRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return enableProdMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "E", function() { return isDevMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "J", function() { return createPlatformFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "B", function() { return NgProbeToken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "M", function() { return APP_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_48", function() { return PACKAGE_ROOT_URL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "H", function() { return PLATFORM_INITIALIZER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "G", function() { return PLATFORM_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_14", function() { return APP_BOOTSTRAP_LISTENER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return APP_INITIALIZER; });
/* unused harmony export ApplicationInitStatus */
/* unused harmony export DebugElement */
/* unused harmony export DebugNode */
/* unused harmony export asNativeElements */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A", function() { return getDebugNode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "O", function() { return Testability; });
/* unused harmony export TestabilityRegistry */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "x", function() { return setTestabilityGetter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_73", function() { return TRANSLATIONS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_26", function() { return TRANSLATIONS_FORMAT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Q", function() { return LOCALE_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_19", function() { return MissingTranslationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "P", function() { return ApplicationModule; });
/* unused harmony export wtfCreateScope */
/* unused harmony export wtfLeave */
/* unused harmony export wtfStartTimeRange */
/* unused harmony export wtfEndTimeRange */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_54", function() { return Type; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return EventEmitter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "L", function() { return ErrorHandler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I", function() { return Sanitizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "F", function() { return SecurityContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_13", function() { return ANALYZE_FOR_ENTRY_COMPONENTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Z", function() { return Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_60", function() { return ContentChild; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_8", function() { return ContentChildren; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_50", function() { return Query; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_15", function() { return ViewChild; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_61", function() { return ViewChildren; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_3", function() { return Component; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return Directive; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_7", function() { return HostBinding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_6", function() { return HostListener; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return Input; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return Output; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_1", function() { return Pipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_57", function() { return CUSTOM_ELEMENTS_SCHEMA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_56", function() { return NO_ERRORS_SCHEMA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return NgModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return ViewEncapsulation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return Version; });
/* unused harmony export VERSION */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return forwardRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_49", function() { return resolveForwardRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return Injector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_9", function() { return ReflectiveInjector; });
/* unused harmony export ResolvedReflectiveFactory */
/* unused harmony export ReflectiveKey */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return InjectionToken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_16", function() { return OpaqueToken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return Inject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return Optional; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return Injectable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return Self; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return SkipSelf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return Host; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "z", function() { return NgZone; });
/* unused harmony export RenderComponentType */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return Renderer; });
/* unused harmony export Renderer2 */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "N", function() { return RendererFactory2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "D", function() { return RendererStyleFlags2; });
/* unused harmony export RootRenderer */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_17", function() { return COMPILER_OPTIONS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_11", function() { return Compiler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_74", function() { return CompilerFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_70", function() { return ModuleWithComponentFactories; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_22", function() { return ComponentFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_23", function() { return ComponentRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "W", function() { return ComponentFactoryResolver; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return ElementRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_5", function() { return NgModuleFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "V", function() { return NgModuleRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_10", function() { return NgModuleFactoryLoader; });
/* unused harmony export getModuleFactory */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_20", function() { return QueryList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_12", function() { return SystemJsNgModuleLoader; });
/* unused harmony export SystemJsNgModuleLoaderConfig */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Y", function() { return TemplateRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "X", function() { return ViewContainerRef; });
/* unused harmony export EmbeddedViewRef */
/* unused harmony export ViewRef */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_4", function() { return ChangeDetectionStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_2", function() { return ChangeDetectorRef; });
/* unused harmony export DefaultIterableDiffer */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "T", function() { return IterableDiffers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "U", function() { return KeyValueDiffers; });
/* unused harmony export SimpleChange */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_0", function() { return WrappedValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "K", function() { return platformCore; });
/* unused harmony export ɵALLOW_MULTIPLE_PLATFORMS */
/* unused harmony export ɵAPP_ID_RANDOM_PROVIDER */
/* unused harmony export ɵValueUnwrapper */
/* unused harmony export ɵdevModeEqual */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "R", function() { return isListLikeIterable; });
/* unused harmony export ɵChangeDetectorStatus */
/* unused harmony export ɵisDefaultChangeDetectionStrategy */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_47", function() { return Console; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_55", function() { return ERROR_COMPONENT_TYPE; });
/* unused harmony export ɵComponentFactory */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_21", function() { return CodegenComponentFactoryResolver; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_53", function() { return LIFECYCLE_HOOKS_VALUES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_52", function() { return LifecycleHooks; });
/* unused harmony export ɵViewMetadata */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_72", function() { return Reflector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_18", function() { return reflector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_59", function() { return ReflectionCapabilities; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_51", function() { return ReflectorReader; });
/* unused harmony export ɵRenderDebugInfo */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return _global; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return looseIdentical; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "S", function() { return stringify; });
/* unused harmony export ɵmakeDecorator */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isObservable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isPromise; });
/* unused harmony export ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_24", function() { return NgModuleInjector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_25", function() { return registerModuleFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_29", function() { return EMPTY_ARRAY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_30", function() { return EMPTY_MAP; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_33", function() { return anchorDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_46", function() { return createComponentFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_45", function() { return createRendererType2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_35", function() { return directiveDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_32", function() { return elementDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_58", function() { return elementEventFullName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_71", function() { return getComponentViewDefinitionFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_27", function() { return inlineInterpolate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_28", function() { return interpolate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_43", function() { return ngContentDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_42", function() { return nodeValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_41", function() { return pipeDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_36", function() { return providerDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_38", function() { return pureArrayDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_39", function() { return pureObjectDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_40", function() { return purePipeDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_37", function() { return queryDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_34", function() { return textDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_44", function() { return unwrapValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_31", function() { return viewDef; });
/* unused harmony export AUTO_STYLE */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_62", function() { return trigger$$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_66", function() { return animate$$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_69", function() { return group$$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_68", function() { return sequence$$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_65", function() { return style$$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_63", function() { return state$$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_67", function() { return keyframes$$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_64", function() { return transition$$1; });
/* unused harmony export ɵba */
/* unused harmony export ɵbb */
/* unused harmony export ɵbf */
/* unused harmony export ɵbc */
/* unused harmony export ɵbe */
/* unused harmony export ɵbd */
/* unused harmony export ɵbg */
/* unused harmony export ɵz */
/* unused harmony export ɵo */
/* unused harmony export ɵl */
/* unused harmony export ɵm */
/* unused harmony export ɵn */
/* unused harmony export ɵf */
/* unused harmony export ɵg */
/* unused harmony export ɵh */
/* unused harmony export ɵi */
/* unused harmony export ɵj */
/* unused harmony export ɵk */
/* unused harmony export ɵc */
/* unused harmony export ɵd */
/* unused harmony export ɵe */
/* unused harmony export ɵp */
/* unused harmony export ɵr */
/* unused harmony export ɵq */
/* unused harmony export ɵu */
/* unused harmony export ɵs */
/* unused harmony export ɵt */
/* unused harmony export ɵa */
/* unused harmony export ɵb */
/* unused harmony export ɵw */
/* unused harmony export ɵx */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.1
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* Creates a token that can be used in a DI Provider.
*
* ### Example ([live demo](http://plnkr.co/edit/Ys9ezXpj2Mnoy3Uc8KBp?p=preview))
*
* ```typescript
* var t = new OpaqueToken("value");
*
* var injector = Injector.resolveAndCreate([
* {provide: t, useValue: "bindingValue"}
* ]);
*
* expect(injector.get(t)).toEqual("bindingValue");
* ```
*
* Using an `OpaqueToken` is preferable to using strings as tokens because of possible collisions
* caused by multiple providers using the same string as two different tokens.
*
* Using an `OpaqueToken` is preferable to using an `Object` as tokens because it provides better
* error messages.
* @deprecated since v4.0.0 because it does not support type information, use `InjectionToken<?>`
* instead.
*/
var OpaqueToken = (function () {
/**
* @param {?} _desc
*/
function OpaqueToken(_desc) {
this._desc = _desc;
}
/**
* @return {?}
*/
OpaqueToken.prototype.toString = function () { return "Token " + this._desc; };
return OpaqueToken;
}());
/**
* Creates a token that can be used in a DI Provider.
*
* Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
* runtime representation) such as when injecting an interface, callable type, array or
* parametrized type.
*
* `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
* the `Injector`. This provides additional level of type safety.
*
* ```
* interface MyInterface {...}
* var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
* // myInterface is inferred to be MyInterface.
* ```
*
* ### Example
*
* {\@example core/di/ts/injector_spec.ts region='InjectionToken'}
*
* \@stable
*/
var InjectionToken = (function (_super) {
__extends(InjectionToken, _super);
/**
* @param {?} desc
*/
function InjectionToken(desc) {
return _super.call(this, desc) || this;
}
/**
* @return {?}
*/
InjectionToken.prototype.toString = function () { return "InjectionToken " + this._desc; };
return InjectionToken;
}(OpaqueToken));
/**
* @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
*/
var __window = typeof window !== 'undefined' && window;
var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
self instanceof WorkerGlobalScope && self;
var __global = typeof global !== 'undefined' && global;
var _global = __window || __global || __self;
var _symbolIterator = null;
/**
* @return {?}
*/
function getSymbolIterator() {
if (!_symbolIterator) {
var /** @type {?} */ Symbol = _global['Symbol'];
if (Symbol && Symbol.iterator) {
_symbolIterator = Symbol.iterator;
}
else {
// es6-shim specific logic
var /** @type {?} */ keys = Object.getOwnPropertyNames(Map.prototype);
for (var /** @type {?} */ i = 0; i < keys.length; ++i) {
var /** @type {?} */ key = keys[i];
if (key !== 'entries' && key !== 'size' &&
((Map)).prototype[key] === Map.prototype['entries']) {
_symbolIterator = key;
}
}
}
}
return _symbolIterator;
}
/**
* @param {?} fn
* @return {?}
*/
function scheduleMicroTask(fn) {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function looseIdentical(a, b) {
return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
}
/**
* @param {?} token
* @return {?}
*/
function stringify(token) {
if (typeof token === 'string') {
return token;
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return "" + token.overriddenName;
}
if (token.name) {
return "" + token.name;
}
var /** @type {?} */ res = token.toString();
if (res == null) {
return '' + res;
}
var /** @type {?} */ newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
/**
* @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
*/
var _nextClassId = 0;
var Reflect = _global['Reflect'];
/**
* @param {?} annotation
* @return {?}
*/
function extractAnnotation(annotation) {
if (typeof annotation === 'function' && annotation.hasOwnProperty('annotation')) {
// it is a decorator, extract annotation
annotation = annotation.annotation;
}
return annotation;
}
/**
* @param {?} fnOrArray
* @param {?} key
* @return {?}
*/
function applyParams(fnOrArray, key) {
if (fnOrArray === Object || fnOrArray === String || fnOrArray === Function ||
fnOrArray === Number || fnOrArray === Array) {
throw new Error("Can not use native " + stringify(fnOrArray) + " as constructor");
}
if (typeof fnOrArray === 'function') {
return fnOrArray;
}
if (Array.isArray(fnOrArray)) {
var /** @type {?} */ annotations = (fnOrArray);
var /** @type {?} */ annoLength = annotations.length - 1;
var /** @type {?} */ fn = fnOrArray[annoLength];
if (typeof fn !== 'function') {
throw new Error("Last position of Class method array must be Function in key " + key + " was '" + stringify(fn) + "'");
}
if (annoLength != fn.length) {
throw new Error("Number of annotations (" + annoLength + ") does not match number of arguments (" + fn.length + ") in the function: " + stringify(fn));
}
var /** @type {?} */ paramsAnnotations = [];
for (var /** @type {?} */ i = 0, /** @type {?} */ ii = annotations.length - 1; i < ii; i++) {
var /** @type {?} */ paramAnnotations = [];
paramsAnnotations.push(paramAnnotations);
var /** @type {?} */ annotation = annotations[i];
if (Array.isArray(annotation)) {
for (var /** @type {?} */ j = 0; j < annotation.length; j++) {
paramAnnotations.push(extractAnnotation(annotation[j]));
}
}
else if (typeof annotation === 'function') {
paramAnnotations.push(extractAnnotation(annotation));
}
else {
paramAnnotations.push(annotation);
}
}
Reflect.defineMetadata('parameters', paramsAnnotations, fn);
return fn;
}
throw new Error("Only Function or Array is supported in Class definition for key '" + key + "' is '" + stringify(fnOrArray) + "'");
}
/**
* Provides a way for expressing ES6 classes with parameter annotations in ES5.
*
* ## Basic Example
*
* ```
* var Greeter = ng.Class({
* constructor: function(name) {
* this.name = name;
* },
*
* greet: function() {
* alert('Hello ' + this.name + '!');
* }
* });
* ```
*
* is equivalent to ES6:
*
* ```
* class Greeter {
* constructor(name) {
* this.name = name;
* }
*
* greet() {
* alert('Hello ' + this.name + '!');
* }
* }
* ```
*
* or equivalent to ES5:
*
* ```
* var Greeter = function (name) {
* this.name = name;
* }
*
* Greeter.prototype.greet = function () {
* alert('Hello ' + this.name + '!');
* }
* ```
*
* ### Example with parameter annotations
*
* ```
* var MyService = ng.Class({
* constructor: [String, [new Optional(), Service], function(name, myService) {
* ...
* }]
* });
* ```
*
* is equivalent to ES6:
*
* ```
* class MyService {
* constructor(name: string, \@Optional() myService: Service) {
* ...
* }
* }
* ```
*
* ### Example with inheritance
*
* ```
* var Shape = ng.Class({
* constructor: (color) {
* this.color = color;
* }
* });
*
* var Square = ng.Class({
* extends: Shape,
* constructor: function(color, size) {
* Shape.call(this, color);
* this.size = size;
* }
* });
* ```
* @suppress {globalThis}
* \@stable
* @param {?} clsDef
* @return {?}
*/
function Class(clsDef) {
var /** @type {?} */ constructor = applyParams(clsDef.hasOwnProperty('constructor') ? clsDef.constructor : undefined, 'constructor');
var /** @type {?} */ proto = constructor.prototype;
if (clsDef.hasOwnProperty('extends')) {
if (typeof clsDef.extends === 'function') {
((constructor)).prototype = proto =
Object.create(((clsDef.extends)).prototype);
}
else {
throw new Error("Class definition 'extends' property must be a constructor function was: " + stringify(clsDef.extends));
}
}
for (var /** @type {?} */ key in clsDef) {
if (key !== 'extends' && key !== 'prototype' && clsDef.hasOwnProperty(key)) {
proto[key] = applyParams(clsDef[key], key);
}
}
if (this && this.annotations instanceof Array) {
Reflect.defineMetadata('annotations', this.annotations, constructor);
}
var /** @type {?} */ constructorName = constructor['name'];
if (!constructorName || constructorName === 'constructor') {
((constructor))['overriddenName'] = "class" + _nextClassId++;
}
return (constructor);
}
/**
* @suppress {globalThis}
* @param {?} name
* @param {?} props
* @param {?=} parentClass
* @param {?=} chainFn
* @return {?}
*/
function makeDecorator(name, props, parentClass, chainFn) {
var /** @type {?} */ metaCtor = makeMetadataCtor([props]);
/**
* @param {?} objOrType
* @return {?}
*/
function DecoratorFactory(objOrType) {
if (!(Reflect && Reflect.getOwnMetadata)) {
throw 'reflect-metadata shim is required when using class decorators';
}
if (this instanceof DecoratorFactory) {
metaCtor.call(this, objOrType);
return this;
}
var /** @type {?} */ annotationInstance = new ((DecoratorFactory))(objOrType);
var /** @type {?} */ chainAnnotation = typeof this === 'function' && Array.isArray(this.annotations) ? this.annotations : [];
chainAnnotation.push(annotationInstance);
var /** @type {?} */ TypeDecorator = (function TypeDecorator(cls) {
var /** @type {?} */ annotations = Reflect.getOwnMetadata('annotations', cls) || [];
annotations.push(annotationInstance);
Reflect.defineMetadata('annotations', annotations, cls);
return cls;
});
TypeDecorator.annotations = chainAnnotation;
TypeDecorator.Class = Class;
if (chainFn)
chainFn(TypeDecorator);
return TypeDecorator;
}
if (parentClass) {
DecoratorFactory.prototype = Object.create(parentClass.prototype);
}
DecoratorFactory.prototype.toString = function () { return "@" + name; };
((DecoratorFactory)).annotationCls = DecoratorFactory;
return DecoratorFactory;
}
/**
* @param {?} props
* @return {?}
*/
function makeMetadataCtor(props) {
return function ctor() {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
props.forEach(function (prop, i) {
var /** @type {?} */ argVal = args[i];
if (Array.isArray(prop)) {
// plain parameter
_this[prop[0]] = argVal === undefined ? prop[1] : argVal;
}
else {
for (var /** @type {?} */ propName in prop) {
_this[propName] =
argVal && argVal.hasOwnProperty(propName) ? argVal[propName] : prop[propName];
}
}
});
};
}
/**
* @param {?} name
* @param {?} props
* @param {?=} parentClass
* @return {?}
*/
function makeParamDecorator(name, props, parentClass) {
var /** @type {?} */ metaCtor = makeMetadataCtor(props);
/**
* @param {...?} args
* @return {?}
*/
function ParamDecoratorFactory() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this instanceof ParamDecoratorFactory) {
metaCtor.apply(this, args);
return this;
}
var /** @type {?} */ annotationInstance = new (((ParamDecoratorFactory)).bind.apply(((ParamDecoratorFactory)), [void 0].concat(args)))();
((ParamDecorator)).annotation = annotationInstance;
return ParamDecorator;
/**
* @param {?} cls
* @param {?} unusedKey
* @param {?} index
* @return {?}
*/
function ParamDecorator(cls, unusedKey, index) {
var /** @type {?} */ parameters = Reflect.getOwnMetadata('parameters', cls) || [];
// there might be gaps if some in between parameters do not have annotations.
// we pad with nulls.
while (parameters.length <= index) {
parameters.push(null);
}
parameters[index] = parameters[index] || []; /** @type {?} */
((parameters[index])).push(annotationInstance);
Reflect.defineMetadata('parameters', parameters, cls);
return cls;
}
}
if (parentClass) {
ParamDecoratorFactory.prototype = Object.create(parentClass.prototype);
}
ParamDecoratorFactory.prototype.toString = function () { return "@" + name; };
((ParamDecoratorFactory)).annotationCls = ParamDecoratorFactory;
return ParamDecoratorFactory;
}
/**
* @param {?} name
* @param {?} props
* @param {?=} parentClass
* @return {?}
*/
function makePropDecorator(name, props, parentClass) {
var /** @type {?} */ metaCtor = makeMetadataCtor(props);
/**
* @param {...?} args
* @return {?}
*/
function PropDecoratorFactory() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this instanceof PropDecoratorFactory) {
metaCtor.apply(this, args);
return this;
}
var /** @type {?} */ decoratorInstance = new (((PropDecoratorFactory)).bind.apply(((PropDecoratorFactory)), [void 0].concat(args)))();
return function PropDecorator(target, name) {
var /** @type {?} */ meta = Reflect.getOwnMetadata('propMetadata', target.constructor) || {};
meta[name] = meta.hasOwnProperty(name) && meta[name] || [];
meta[name].unshift(decoratorInstance);
Reflect.defineMetadata('propMetadata', meta, target.constructor);
};
}
if (parentClass) {
PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
}
PropDecoratorFactory.prototype.toString = function () { return "@" + name; };
((PropDecoratorFactory)).annotationCls = PropDecoratorFactory;
return PropDecoratorFactory;
}
/**
* @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
*/
/**
* This token can be used to create a virtual provider that will populate the
* `entryComponents` fields of components and ng modules based on its `useValue`.
* All components that are referenced in the `useValue` value (either directly
* or in a nested array or map) will be added to the `entryComponents` property.
*
* ### Example
* The following example shows how the router can populate the `entryComponents`
* field of an NgModule based on the router configuration which refers
* to components.
*
* ```typescript
* // helper function inside the router
* function provideRoutes(routes) {
* return [
* {provide: ROUTES, useValue: routes},
* {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: routes, multi: true}
* ];
* }
*
* // user code
* let routes = [
* {path: '/root', component: RootComp},
* {path: '/teams', component: TeamsComp}
* ];
*
* \@NgModule({
* providers: [provideRoutes(routes)]
* })
* class ModuleWithRoutes {}
* ```
*
* \@experimental
*/
var ANALYZE_FOR_ENTRY_COMPONENTS = new InjectionToken('AnalyzeForEntryComponents');
/**
* Attribute decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Attribute = makeParamDecorator('Attribute', [['attributeName', undefined]]);
/**
* Base class for query metadata.
*
* See {\@link ContentChildren}, {\@link ContentChild}, {\@link ViewChildren}, {\@link ViewChild} for
* more information.
*
* \@stable
* @abstract
*/
var Query = (function () {
function Query() {
}
return Query;
}());
/**
* ContentChildren decorator and metadata.
*
* \@stable
* \@Annotation
*/
var ContentChildren = makePropDecorator('ContentChildren', [
['selector', undefined], {
first: false,
isViewQuery: false,
descendants: false,
read: undefined,
}
], Query);
/**
* ContentChild decorator and metadata.
*
* \@stable
* \@Annotation
*/
var ContentChild = makePropDecorator('ContentChild', [
['selector', undefined], {
first: true,
isViewQuery: false,
descendants: true,
read: undefined,
}
], Query);
/**
* ViewChildren decorator and metadata.
*
* \@stable
* \@Annotation
*/
var ViewChildren = makePropDecorator('ViewChildren', [
['selector', undefined], {
first: false,
isViewQuery: true,
descendants: true,
read: undefined,
}
], Query);
/**
* ViewChild decorator and metadata.
*
* \@stable
* \@Annotation
*/
var ViewChild = makePropDecorator('ViewChild', [
['selector', undefined], {
first: true,
isViewQuery: true,
descendants: true,
read: undefined,
}
], Query);
var ChangeDetectionStrategy = {};
ChangeDetectionStrategy.OnPush = 0;
ChangeDetectionStrategy.Default = 1;
ChangeDetectionStrategy[ChangeDetectionStrategy.OnPush] = "OnPush";
ChangeDetectionStrategy[ChangeDetectionStrategy.Default] = "Default";
var ChangeDetectorStatus = {};
ChangeDetectorStatus.CheckOnce = 0;
ChangeDetectorStatus.Checked = 1;
ChangeDetectorStatus.CheckAlways = 2;
ChangeDetectorStatus.Detached = 3;
ChangeDetectorStatus.Errored = 4;
ChangeDetectorStatus.Destroyed = 5;
ChangeDetectorStatus[ChangeDetectorStatus.CheckOnce] = "CheckOnce";
ChangeDetectorStatus[ChangeDetectorStatus.Checked] = "Checked";
ChangeDetectorStatus[ChangeDetectorStatus.CheckAlways] = "CheckAlways";
ChangeDetectorStatus[ChangeDetectorStatus.Detached] = "Detached";
ChangeDetectorStatus[ChangeDetectorStatus.Errored] = "Errored";
ChangeDetectorStatus[ChangeDetectorStatus.Destroyed] = "Destroyed";
/**
* @param {?} changeDetectionStrategy
* @return {?}
*/
function isDefaultChangeDetectionStrategy(changeDetectionStrategy) {
return changeDetectionStrategy == null ||
changeDetectionStrategy === ChangeDetectionStrategy.Default;
}
/**
* @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
*/
/**
* Directive decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Directive = makeDecorator('Directive', {
selector: undefined,
inputs: undefined,
outputs: undefined,
host: undefined,
providers: undefined,
exportAs: undefined,
queries: undefined
});
/**
* Component decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Component = makeDecorator('Component', {
selector: undefined,
inputs: undefined,
outputs: undefined,
host: undefined,
exportAs: undefined,
moduleId: undefined,
providers: undefined,
viewProviders: undefined,
changeDetection: ChangeDetectionStrategy.Default,
queries: undefined,
templateUrl: undefined,
template: undefined,
styleUrls: undefined,
styles: undefined,
animations: undefined,
encapsulation: undefined,
interpolation: undefined,
entryComponents: undefined
}, Directive);
/**
* Pipe decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Pipe = makeDecorator('Pipe', {
name: undefined,
pure: true,
});
/**
* Input decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Input = makePropDecorator('Input', [['bindingPropertyName', undefined]]);
/**
* Output decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Output = makePropDecorator('Output', [['bindingPropertyName', undefined]]);
/**
* HostBinding decorator and metadata.
*
* \@stable
* \@Annotation
*/
var HostBinding = makePropDecorator('HostBinding', [['hostPropertyName', undefined]]);
/**
* HostListener decorator and metadata.
*
* \@stable
* \@Annotation
*/
var HostListener = makePropDecorator('HostListener', [['eventName', undefined], ['args', []]]);
/**
* @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
*/
/**
* Defines a schema that will allow:
* - any non-Angular elements with a `-` in their name,
* - any properties on elements with a `-` in their name which is the common rule for custom
* elements.
*
* \@stable
*/
var CUSTOM_ELEMENTS_SCHEMA = {
name: 'custom-elements'
};
/**
* Defines a schema that will allow any property on any element.
*
* \@experimental
*/
var NO_ERRORS_SCHEMA = {
name: 'no-errors-schema'
};
/**
* NgModule decorator and metadata.
*
* \@stable
* \@Annotation
*/
var NgModule = makeDecorator('NgModule', {
providers: undefined,
declarations: undefined,
imports: undefined,
exports: undefined,
entryComponents: undefined,
bootstrap: undefined,
schemas: undefined,
id: undefined,
});
var ViewEncapsulation = {};
ViewEncapsulation.Emulated = 0;
ViewEncapsulation.Native = 1;
ViewEncapsulation.None = 2;
ViewEncapsulation[ViewEncapsulation.Emulated] = "Emulated";
ViewEncapsulation[ViewEncapsulation.Native] = "Native";
ViewEncapsulation[ViewEncapsulation.None] = "None";
/**
* Metadata properties available for configuring Views.
*
* For details on the `\@Component` annotation, see {\@link Component}.
*
* ### Example
*
* ```
* \@Component({
* selector: 'greet',
* template: 'Hello {{name}}!',
* })
* class Greet {
* name: string;
*
* constructor() {
* this.name = 'World';
* }
* }
* ```
*
* @deprecated Use Component instead.
*
* {\@link Component}
*/
var ViewMetadata = (function () {
/**
* @param {?=} __0
*/
function ViewMetadata(_a) {
var _b = _a === void 0 ? {} : _a, templateUrl = _b.templateUrl, template = _b.template, encapsulation = _b.encapsulation, styles = _b.styles, styleUrls = _b.styleUrls, animations = _b.animations, interpolation = _b.interpolation;
this.templateUrl = templateUrl;
this.template = template;
this.styleUrls = styleUrls;
this.styles = styles;
this.encapsulation = encapsulation;
this.animations = animations;
this.interpolation = interpolation;
}
return ViewMetadata;
}());
/**
* @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
*/
/**
* \@whatItDoes Represents the version of Angular
*
* \@stable
*/
var Version = (function () {
/**
* @param {?} full
*/
function Version(full) {
this.full = full;
}
Object.defineProperty(Version.prototype, "major", {
/**
* @return {?}
*/
get: function () { return this.full.split('.')[0]; },
enumerable: true,
configurable: true
});
Object.defineProperty(Version.prototype, "minor", {
/**
* @return {?}
*/
get: function () { return this.full.split('.')[1]; },
enumerable: true,
configurable: true
});
Object.defineProperty(Version.prototype, "patch", {
/**
* @return {?}
*/
get: function () { return this.full.split('.').slice(2).join('.'); },
enumerable: true,
configurable: true
});
return Version;
}());
/**
* \@stable
*/
var VERSION = new Version('4.1.1');
/**
* @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
*/
/**
* Inject decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Inject = makeParamDecorator('Inject', [['token', undefined]]);
/**
* Optional decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Optional = makeParamDecorator('Optional', []);
/**
* Injectable decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Injectable = makeDecorator('Injectable', []);
/**
* Self decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Self = makeParamDecorator('Self', []);
/**
* SkipSelf decorator and metadata.
*
* \@stable
* \@Annotation
*/
var SkipSelf = makeParamDecorator('SkipSelf', []);
/**
* Host decorator and metadata.
*
* \@stable
* \@Annotation
*/
var Host = makeParamDecorator('Host', []);
/**
* @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
*/
/**
* Allows to refer to references which are not yet defined.
*
* For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
* DI is declared,
* but not yet defined. It is also used when the `token` which we use when creating a query is not
* yet defined.
*
* ### Example
* {\@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
* \@experimental
* @param {?} forwardRefFn
* @return {?}
*/
function forwardRef(forwardRefFn) {
((forwardRefFn)).__forward_ref__ = forwardRef;
((forwardRefFn)).toString = function () { return stringify(this()); };
return (((forwardRefFn)));
}
/**
* Lazily retrieves the reference value from a forwardRef.
*
* Acts as the identity function when given a non-forward-ref value.
*
* ### Example ([live demo](http://plnkr.co/edit/GU72mJrk1fiodChcmiDR?p=preview))
*
* {\@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
*
* See: {\@link forwardRef}
* \@experimental
* @param {?} type
* @return {?}
*/
function resolveForwardRef(type) {
if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__') &&
type.__forward_ref__ === forwardRef) {
return ((type))();
}
else {
return type;
}
}
/**
* @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
*/
var _THROW_IF_NOT_FOUND = new Object();
var THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
var _NullInjector = (function () {
function _NullInjector() {
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
_NullInjector.prototype.get = function (token, notFoundValue) {
if (notFoundValue === void 0) { notFoundValue = _THROW_IF_NOT_FOUND; }
if (notFoundValue === _THROW_IF_NOT_FOUND) {
throw new Error("No provider for " + stringify(token) + "!");
}
return notFoundValue;
};
return _NullInjector;
}());
/**
* \@whatItDoes Injector interface
* \@howToUse
* ```
* const injector: Injector = ...;
* injector.get(...);
* ```
*
* \@description
* For more details, see the {\@linkDocs guide/dependency-injection "Dependency Injection Guide"}.
*
* ### Example
*
* {\@example core/di/ts/injector_spec.ts region='Injector'}
*
* `Injector` returns itself when given `Injector` as a token:
* {\@example core/di/ts/injector_spec.ts region='injectInjector'}
*
* \@stable
* @abstract
*/
var Injector = (function () {
function Injector() {
}
/**
* Retrieves an instance from the injector based on the provided token.
* If not found:
* - Throws an error if no `notFoundValue` that is not equal to
* Injector.THROW_IF_NOT_FOUND is given
* - Returns the `notFoundValue` otherwise
* @abstract
* @template T
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
Injector.prototype.get = function (token, notFoundValue) { };
/**
* @deprecated from v4.0.0 use Type<T> or InjectionToken<T>
* @suppress {duplicate}
* @abstract
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
Injector.prototype.get = function (token, notFoundValue) { };
return Injector;
}());
Injector.THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
Injector.NULL = new _NullInjector();
/**
* @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
*/
var ERROR_COMPONENT_TYPE = 'ngComponentType';
var ERROR_DEBUG_CONTEXT = 'ngDebugContext';
var ERROR_ORIGINAL_ERROR = 'ngOriginalError';
var ERROR_LOGGER = 'ngErrorLogger';
/**
* @param {?} error
* @return {?}
*/
/**
* @param {?} error
* @return {?}
*/
function getDebugContext(error) {
return ((error))[ERROR_DEBUG_CONTEXT];
}
/**
* @param {?} error
* @return {?}
*/
function getOriginalError(error) {
return ((error))[ERROR_ORIGINAL_ERROR];
}
/**
* @param {?} error
* @return {?}
*/
function getErrorLogger(error) {
return ((error))[ERROR_LOGGER] || defaultErrorLogger;
}
/**
* @param {?} console
* @param {...?} values
* @return {?}
*/
function defaultErrorLogger(console) {
var values = [];
for (var _i = 1; _i < arguments.length; _i++) {
values[_i - 1] = arguments[_i];
}
console.error.apply(console, values);
}
/**
* @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
*/
/**
* \@whatItDoes Provides a hook for centralized exception handling.
*
* \@description
*
* The default implementation of `ErrorHandler` prints error messages to the `console`. To
* intercept error handling, write a custom exception handler that replaces this default as
* appropriate for your app.
*
* ### Example
*
* ```
* class MyErrorHandler implements ErrorHandler {
* handleError(error) {
* // do something with the exception
* }
* }
*
* \@NgModule({
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
* class MyModule {}
* ```
*
* \@stable
*/
var ErrorHandler = (function () {
/**
* @param {?=} deprecatedParameter
*/
function ErrorHandler(
/**
* @deprecated since v4.0 parameter no longer has an effect, as ErrorHandler will never
* rethrow.
*/
deprecatedParameter) {
/**
* \@internal
*/
this._console = console;
}
/**
* @param {?} error
* @return {?}
*/
ErrorHandler.prototype.handleError = function (error) {
var /** @type {?} */ originalError = this._findOriginalError(error);
var /** @type {?} */ context = this._findContext(error);
// Note: Browser consoles show the place from where console.error was called.
// We can use this to give users additional information about the error.
var /** @type {?} */ errorLogger = getErrorLogger(error);
errorLogger(this._console, "ERROR", error);
if (originalError) {
errorLogger(this._console, "ORIGINAL ERROR", originalError);
}
if (context) {
errorLogger(this._console, 'ERROR CONTEXT', context);
}
};
/**
* \@internal
* @param {?} error
* @return {?}
*/
ErrorHandler.prototype._findContext = function (error) {
if (error) {
return getDebugContext(error) ? getDebugContext(error) :
this._findContext(getOriginalError(error));
}
return null;
};
/**
* \@internal
* @param {?} error
* @return {?}
*/
ErrorHandler.prototype._findOriginalError = function (error) {
var /** @type {?} */ e = getOriginalError(error);
while (e && getOriginalError(e)) {
e = getOriginalError(e);
}
return e;
};
return ErrorHandler;
}());
/**
* @param {?} message
* @param {?} originalError
* @return {?}
*/
function wrappedError(message, originalError) {
var /** @type {?} */ msg = message + " caused by: " + (originalError instanceof Error ? originalError.message : originalError);
var /** @type {?} */ error = Error(msg);
((error))[ERROR_ORIGINAL_ERROR] = originalError;
return error;
}
/**
* @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
*/
/**
* @param {?} keys
* @return {?}
*/
function findFirstClosedCycle(keys) {
var /** @type {?} */ res = [];
for (var /** @type {?} */ i = 0; i < keys.length; ++i) {
if (res.indexOf(keys[i]) > -1) {
res.push(keys[i]);
return res;
}
res.push(keys[i]);
}
return res;
}
/**
* @param {?} keys
* @return {?}
*/
function constructResolvingPath(keys) {
if (keys.length > 1) {
var /** @type {?} */ reversed = findFirstClosedCycle(keys.slice().reverse());
var /** @type {?} */ tokenStrs = reversed.map(function (k) { return stringify(k.token); });
return ' (' + tokenStrs.join(' -> ') + ')';
}
return '';
}
/**
* @param {?} injector
* @param {?} key
* @param {?} constructResolvingMessage
* @param {?=} originalError
* @return {?}
*/
function injectionError(injector, key, constructResolvingMessage, originalError) {
var /** @type {?} */ error = ((originalError ? wrappedError('', originalError) : Error()));
error.addKey = addKey;
error.keys = [key];
error.injectors = [injector];
error.constructResolvingMessage = constructResolvingMessage;
error.message = error.constructResolvingMessage();
((error))[ERROR_ORIGINAL_ERROR] = originalError;
return error;
}
/**
* @this {?}
* @param {?} injector
* @param {?} key
* @return {?}
*/
function addKey(injector, key) {
this.injectors.push(injector);
this.keys.push(key);
this.message = this.constructResolvingMessage();
}
/**
* Thrown when trying to retrieve a dependency by key from {\@link Injector}, but the
* {\@link Injector} does not have a {\@link Provider} for the given key.
*
* ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
*
* ```typescript
* class A {
* constructor(b:B) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
* @param {?} injector
* @param {?} key
* @return {?}
*/
function noProviderError(injector, key) {
return injectionError(injector, key, function () {
var /** @type {?} */ first = stringify(this.keys[0].token);
return "No provider for " + first + "!" + constructResolvingPath(this.keys);
});
}
/**
* Thrown when dependencies form a cycle.
*
* ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* {provide: "one", useFactory: (two) => "two", deps: [[new Inject("two")]]},
* {provide: "two", useFactory: (one) => "one", deps: [[new Inject("one")]]}
* ]);
*
* expect(() => injector.get("one")).toThrowError();
* ```
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
* @param {?} injector
* @param {?} key
* @return {?}
*/
function cyclicDependencyError(injector, key) {
return injectionError(injector, key, function () {
return "Cannot instantiate cyclic dependency!" + constructResolvingPath(this.keys);
});
}
/**
* Thrown when a constructing type returns with an Error.
*
* The `InstantiationError` class contains the original error plus the dependency graph which caused
* this object to be instantiated.
*
* ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
*
* ```typescript
* class A {
* constructor() {
* throw new Error('message');
* }
* }
*
* var injector = Injector.resolveAndCreate([A]);
* try {
* injector.get(A);
* } catch (e) {
* expect(e instanceof InstantiationError).toBe(true);
* expect(e.originalException.message).toEqual("message");
* expect(e.originalStack).toBeDefined();
* }
* ```
* @param {?} injector
* @param {?} originalException
* @param {?} originalStack
* @param {?} key
* @return {?}
*/
function instantiationError(injector, originalException, originalStack, key) {
return injectionError(injector, key, function () {
var /** @type {?} */ first = stringify(this.keys[0].token);
return getOriginalError(this).message + ": Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + ".";
}, originalException);
}
/**
* Thrown when an object other then {\@link Provider} (or `Type`) is passed to {\@link Injector}
* creation.
*
* ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
*
* ```typescript
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
* ```
* @param {?} provider
* @return {?}
*/
function invalidProviderError(provider) {
return Error("Invalid provider - only instances of Provider and Type are allowed, got: " + provider);
}
/**
* Thrown when the class has no annotation information.
*
* Lack of annotation information prevents the {\@link Injector} from determining which dependencies
* need to be injected into the constructor.
*
* ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
*
* ```typescript
* class A {
* constructor(b) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*
* This error is also thrown when the class not marked with {\@link Injectable} has parameter types.
*
* ```typescript
* class B {}
*
* class A {
* constructor(b:B) {} // no information about the parameter types of A is available at runtime.
* }
*
* expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
* ```
* \@stable
* @param {?} typeOrFunc
* @param {?} params
* @return {?}
*/
function noAnnotationError(typeOrFunc, params) {
var /** @type {?} */ signature = [];
for (var /** @type {?} */ i = 0, /** @type {?} */ ii = params.length; i < ii; i++) {
var /** @type {?} */ parameter = params[i];
if (!parameter || parameter.length == 0) {
signature.push('?');
}
else {
signature.push(parameter.map(stringify).join(' '));
}
}
return Error('Cannot resolve all parameters for \'' + stringify(typeOrFunc) + '\'(' +
signature.join(', ') + '). ' +
'Make sure that all the parameters are decorated with Inject or have valid type annotations and that \'' +
stringify(typeOrFunc) + '\' is decorated with Injectable.');
}
/**
* Thrown when getting an object by index.
*
* ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
*
* ```typescript
* class A {}
*
* var injector = Injector.resolveAndCreate([A]);
*
* expect(() => injector.getAt(100)).toThrowError();
* ```
* \@stable
* @param {?} index
* @return {?}
*/
function outOfBoundsError(index) {
return Error("Index " + index + " is out-of-bounds.");
}
/**
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* { provide: "Strings", useValue: "string1", multi: true},
* { provide: "Strings", useValue: "string2", multi: false}
* ])).toThrowError();
* ```
* @param {?} provider1
* @param {?} provider2
* @return {?}
*/
function mixingMultiProvidersWithRegularProvidersError(provider1, provider2) {
return Error("Cannot mix multi providers and regular providers, got: " + provider1 + " " + provider2);
}
/**
* @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
*/
/**
* A unique object used for retrieving items from the {\@link ReflectiveInjector}.
*
* Keys have:
* - a system-wide unique `id`.
* - a `token`.
*
* `Key` is used internally by {\@link ReflectiveInjector} because its system-wide unique `id` allows
* the
* injector to store created objects in a more efficient way.
*
* `Key` should not be created directly. {\@link ReflectiveInjector} creates keys automatically when
* resolving
* providers.
* \@experimental
*/
var ReflectiveKey = (function () {
/**
* Private
* @param {?} token
* @param {?} id
*/
function ReflectiveKey(token, id) {
this.token = token;
this.id = id;
if (!token) {
throw new Error('Token must be defined!');
}
}
Object.defineProperty(ReflectiveKey.prototype, "displayName", {
/**
* Returns a stringified token.
* @return {?}
*/
get: function () { return stringify(this.token); },
enumerable: true,
configurable: true
});
/**
* Retrieves a `Key` for a token.
* @param {?} token
* @return {?}
*/
ReflectiveKey.get = function (token) {
return _globalKeyRegistry.get(resolveForwardRef(token));
};
Object.defineProperty(ReflectiveKey, "numberOfKeys", {
/**
* @return {?} the number of keys registered in the system.
*/
get: function () { return _globalKeyRegistry.numberOfKeys; },
enumerable: true,
configurable: true
});
return ReflectiveKey;
}());
/**
* \@internal
*/
var KeyRegistry = (function () {
function KeyRegistry() {
this._allKeys = new Map();
}
/**
* @param {?} token
* @return {?}
*/
KeyRegistry.prototype.get = function (token) {
if (token instanceof ReflectiveKey)
return token;
if (this._allKeys.has(token)) {
return ((this._allKeys.get(token)));
}
var /** @type {?} */ newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys);
this._allKeys.set(token, newKey);
return newKey;
};
Object.defineProperty(KeyRegistry.prototype, "numberOfKeys", {
/**
* @return {?}
*/
get: function () { return this._allKeys.size; },
enumerable: true,
configurable: true
});
return KeyRegistry;
}());
var _globalKeyRegistry = new KeyRegistry();
/**
* \@whatItDoes Represents a type that a Component or other object is instances of.
*
* \@description
*
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
* the `MyCustomComponent` constructor function.
*
* \@stable
*/
var Type = Function;
/**
* @param {?} v
* @return {?}
*/
function isType(v) {
return typeof v === 'function';
}
/**
* @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
*/
/**
* Attention: This regex has to hold even if the code is minified!
*/
var DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/;
var ReflectionCapabilities = (function () {
/**
* @param {?=} reflect
*/
function ReflectionCapabilities(reflect) {
this._reflect = reflect || _global['Reflect'];
}
/**
* @return {?}
*/
ReflectionCapabilities.prototype.isReflectionEnabled = function () { return true; };
/**
* @template T
* @param {?} t
* @return {?}
*/
ReflectionCapabilities.prototype.factory = function (t) { return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new (t.bind.apply(t, [void 0].concat(args)))();
}; };
/**
* \@internal
* @param {?} paramTypes
* @param {?} paramAnnotations
* @return {?}
*/
ReflectionCapabilities.prototype._zipTypesAndAnnotations = function (paramTypes, paramAnnotations) {
var /** @type {?} */ result;
if (typeof paramTypes === 'undefined') {
result = new Array(paramAnnotations.length);
}
else {
result = new Array(paramTypes.length);
}
for (var /** @type {?} */ i = 0; i < result.length; i++) {
// TS outputs Object for parameters without types, while Traceur omits
// the annotations. For now we preserve the Traceur behavior to aid
// migration, but this can be revisited.
if (typeof paramTypes === 'undefined') {
result[i] = [];
}
else if (paramTypes[i] != Object) {
result[i] = [paramTypes[i]];
}
else {
result[i] = [];
}
if (paramAnnotations && paramAnnotations[i] != null) {
result[i] = result[i].concat(paramAnnotations[i]);
}
}
return result;
};
/**
* @param {?} type
* @param {?} parentCtor
* @return {?}
*/
ReflectionCapabilities.prototype._ownParameters = function (type, parentCtor) {
// If we have no decorators, we only have function.length as metadata.
// In that case, to detect whether a child class declared an own constructor or not,
// we need to look inside of that constructor to check whether it is
// just calling the parent.
// This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
// that sets 'design:paramtypes' to []
// if a class inherits from another class but has no ctor declared itself.
if (DELEGATE_CTOR.exec(type.toString())) {
return null;
}
// Prefer the direct API.
if (((type)).parameters && ((type)).parameters !== parentCtor.parameters) {
return ((type)).parameters;
}
// API of tsickle for lowering decorators to properties on the class.
var /** @type {?} */ tsickleCtorParams = ((type)).ctorParameters;
if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
// Newer tsickle uses a function closure
// Retain the non-function case for compatibility with older tsickle
var /** @type {?} */ ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
var /** @type {?} */ paramTypes = ctorParameters.map(function (ctorParam) { return ctorParam && ctorParam.type; });
var /** @type {?} */ paramAnnotations = ctorParameters.map(function (ctorParam) { return ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators); });
return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
}
// API for metadata created by invoking the decorators.
if (this._reflect != null && this._reflect.getOwnMetadata != null) {
var /** @type {?} */ paramAnnotations = this._reflect.getOwnMetadata('parameters', type);
var /** @type {?} */ paramTypes = this._reflect.getOwnMetadata('design:paramtypes', type);
if (paramTypes || paramAnnotations) {
return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
}
}
// If a class has no decorators, at least create metadata
// based on function.length.
// Note: We know that this is a real constructor as we checked
// the content of the constructor above.
return new Array(((type.length))).fill(undefined);
};
/**
* @param {?} type
* @return {?}
*/
ReflectionCapabilities.prototype.parameters = function (type) {
// Note: only report metadata if we have at least one class decorator
// to stay in sync with the static reflector.
if (!isType(type)) {
return [];
}
var /** @type {?} */ parentCtor = getParentCtor(type);
var /** @type {?} */ parameters = this._ownParameters(type, parentCtor);
if (!parameters && parentCtor !== Object) {
parameters = this.parameters(parentCtor);
}
return parameters || [];
};
/**
* @param {?} typeOrFunc
* @param {?} parentCtor
* @return {?}
*/
ReflectionCapabilities.prototype._ownAnnotations = function (typeOrFunc, parentCtor) {
// Prefer the direct API.
if (((typeOrFunc)).annotations && ((typeOrFunc)).annotations !== parentCtor.annotations) {
var /** @type {?} */ annotations = ((typeOrFunc)).annotations;
if (typeof annotations === 'function' && annotations.annotations) {
annotations = annotations.annotations;
}
return annotations;
}
// API of tsickle for lowering decorators to properties on the class.
if (((typeOrFunc)).decorators && ((typeOrFunc)).decorators !== parentCtor.decorators) {
return convertTsickleDecoratorIntoMetadata(((typeOrFunc)).decorators);
}
// API for metadata created by invoking the decorators.
if (this._reflect && this._reflect.getOwnMetadata) {
return this._reflect.getOwnMetadata('annotations', typeOrFunc);
}
return null;
};
/**
* @param {?} typeOrFunc
* @return {?}
*/
ReflectionCapabilities.prototype.annotations = function (typeOrFunc) {
if (!isType(typeOrFunc)) {
return [];
}
var /** @type {?} */ parentCtor = getParentCtor(typeOrFunc);
var /** @type {?} */ ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
var /** @type {?} */ parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
return parentAnnotations.concat(ownAnnotations);
};
/**
* @param {?} typeOrFunc
* @param {?} parentCtor
* @return {?}
*/
ReflectionCapabilities.prototype._ownPropMetadata = function (typeOrFunc, parentCtor) {
// Prefer the direct API.
if (((typeOrFunc)).propMetadata &&
((typeOrFunc)).propMetadata !== parentCtor.propMetadata) {
var /** @type {?} */ propMetadata = ((typeOrFunc)).propMetadata;
if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
propMetadata = propMetadata.propMetadata;
}
return propMetadata;
}
// API of tsickle for lowering decorators to properties on the class.
if (((typeOrFunc)).propDecorators &&
((typeOrFunc)).propDecorators !== parentCtor.propDecorators) {
var /** @type {?} */ propDecorators_1 = ((typeOrFunc)).propDecorators;
var /** @type {?} */ propMetadata_1 = ({});
Object.keys(propDecorators_1).forEach(function (prop) {
propMetadata_1[prop] = convertTsickleDecoratorIntoMetadata(propDecorators_1[prop]);
});
return propMetadata_1;
}
// API for metadata created by invoking the decorators.
if (this._reflect && this._reflect.getOwnMetadata) {
return this._reflect.getOwnMetadata('propMetadata', typeOrFunc);
}
return null;
};
/**
* @param {?} typeOrFunc
* @return {?}
*/
ReflectionCapabilities.prototype.propMetadata = function (typeOrFunc) {
if (!isType(typeOrFunc)) {
return {};
}
var /** @type {?} */ parentCtor = getParentCtor(typeOrFunc);
var /** @type {?} */ propMetadata = {};
if (parentCtor !== Object) {
var /** @type {?} */ parentPropMetadata_1 = this.propMetadata(parentCtor);
Object.keys(parentPropMetadata_1).forEach(function (propName) {
propMetadata[propName] = parentPropMetadata_1[propName];
});
}
var /** @type {?} */ ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
if (ownPropMetadata) {
Object.keys(ownPropMetadata).forEach(function (propName) {
var /** @type {?} */ decorators = [];
if (propMetadata.hasOwnProperty(propName)) {
decorators.push.apply(decorators, propMetadata[propName]);
}
decorators.push.apply(decorators, ownPropMetadata[propName]);
propMetadata[propName] = decorators;
});
}
return propMetadata;
};
/**
* @param {?} type
* @param {?} lcProperty
* @return {?}
*/
ReflectionCapabilities.prototype.hasLifecycleHook = function (type, lcProperty) {
return type instanceof Type && lcProperty in type.prototype;
};
/**
* @param {?} name
* @return {?}
*/
ReflectionCapabilities.prototype.getter = function (name) { return (new Function('o', 'return o.' + name + ';')); };
/**
* @param {?} name
* @return {?}
*/
ReflectionCapabilities.prototype.setter = function (name) {
return (new Function('o', 'v', 'return o.' + name + ' = v;'));
};
/**
* @param {?} name
* @return {?}
*/
ReflectionCapabilities.prototype.method = function (name) {
var /** @type {?} */ functionBody = "if (!o." + name + ") throw new Error('\"" + name + "\" is undefined');\n return o." + name + ".apply(o, args);";
return (new Function('o', 'args', functionBody));
};
/**
* @param {?} type
* @return {?}
*/
ReflectionCapabilities.prototype.importUri = function (type) {
// StaticSymbol
if (typeof type === 'object' && type['filePath']) {
return type['filePath'];
}
// Runtime type
return "./" + stringify(type);
};
/**
* @param {?} type
* @return {?}
*/
ReflectionCapabilities.prototype.resourceUri = function (type) { return "./" + stringify(type); };
/**
* @param {?} name
* @param {?} moduleUrl
* @param {?} members
* @param {?} runtime
* @return {?}
*/
ReflectionCapabilities.prototype.resolveIdentifier = function (name, moduleUrl, members, runtime) {
return runtime;
};
/**
* @param {?} enumIdentifier
* @param {?} name
* @return {?}
*/
ReflectionCapabilities.prototype.resolveEnum = function (enumIdentifier, name) { return enumIdentifier[name]; };
return ReflectionCapabilities;
}());
/**
* @param {?} decoratorInvocations
* @return {?}
*/
function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
if (!decoratorInvocations) {
return [];
}
return decoratorInvocations.map(function (decoratorInvocation) {
var /** @type {?} */ decoratorType = decoratorInvocation.type;
var /** @type {?} */ annotationCls = decoratorType.annotationCls;
var /** @type {?} */ annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
return new (annotationCls.bind.apply(annotationCls, [void 0].concat(annotationArgs)))();
});
}
/**
* @param {?} ctor
* @return {?}
*/
function getParentCtor(ctor) {
var /** @type {?} */ parentProto = Object.getPrototypeOf(ctor.prototype);
var /** @type {?} */ parentCtor = parentProto ? parentProto.constructor : null;
// Note: We always use `Object` as the null value
// to simplify checking later on.
return parentCtor || Object;
}
/**
* Provides read-only access to reflection data about symbols. Used internally by Angular
* to power dependency injection and compilation.
* @abstract
*/
var ReflectorReader = (function () {
function ReflectorReader() {
}
/**
* @abstract
* @param {?} typeOrFunc
* @return {?}
*/
ReflectorReader.prototype.parameters = function (typeOrFunc) { };
/**
* @abstract
* @param {?} typeOrFunc
* @return {?}
*/
ReflectorReader.prototype.annotations = function (typeOrFunc) { };
/**
* @abstract
* @param {?} typeOrFunc
* @return {?}
*/
ReflectorReader.prototype.propMetadata = function (typeOrFunc) { };
/**
* @abstract
* @param {?} typeOrFunc
* @return {?}
*/
ReflectorReader.prototype.importUri = function (typeOrFunc) { };
/**
* @abstract
* @param {?} typeOrFunc
* @return {?}
*/
ReflectorReader.prototype.resourceUri = function (typeOrFunc) { };
/**
* @abstract
* @param {?} name
* @param {?} moduleUrl
* @param {?} members
* @param {?} runtime
* @return {?}
*/
ReflectorReader.prototype.resolveIdentifier = function (name, moduleUrl, members, runtime) { };
/**
* @abstract
* @param {?} identifier
* @param {?} name
* @return {?}
*/
ReflectorReader.prototype.resolveEnum = function (identifier, name) { };
return ReflectorReader;
}());
/**
* @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
*/
/**
* Provides access to reflection data about symbols. Used internally by Angular
* to power dependency injection and compilation.
*/
var Reflector = (function (_super) {
__extends(Reflector, _super);
/**
* @param {?} reflectionCapabilities
*/
function Reflector(reflectionCapabilities) {
var _this = _super.call(this) || this;
_this.reflectionCapabilities = reflectionCapabilities;
return _this;
}
/**
* @param {?} caps
* @return {?}
*/
Reflector.prototype.updateCapabilities = function (caps) { this.reflectionCapabilities = caps; };
/**
* @param {?} type
* @return {?}
*/
Reflector.prototype.factory = function (type) { return this.reflectionCapabilities.factory(type); };
/**
* @param {?} typeOrFunc
* @return {?}
*/
Reflector.prototype.parameters = function (typeOrFunc) {
return this.reflectionCapabilities.parameters(typeOrFunc);
};
/**
* @param {?} typeOrFunc
* @return {?}
*/
Reflector.prototype.annotations = function (typeOrFunc) {
return this.reflectionCapabilities.annotations(typeOrFunc);
};
/**
* @param {?} typeOrFunc
* @return {?}
*/
Reflector.prototype.propMetadata = function (typeOrFunc) {
return this.reflectionCapabilities.propMetadata(typeOrFunc);
};
/**
* @param {?} type
* @param {?} lcProperty
* @return {?}
*/
Reflector.prototype.hasLifecycleHook = function (type, lcProperty) {
return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty);
};
/**
* @param {?} name
* @return {?}
*/
Reflector.prototype.getter = function (name) { return this.reflectionCapabilities.getter(name); };
/**
* @param {?} name
* @return {?}
*/
Reflector.prototype.setter = function (name) { return this.reflectionCapabilities.setter(name); };
/**
* @param {?} name
* @return {?}
*/
Reflector.prototype.method = function (name) { return this.reflectionCapabilities.method(name); };
/**
* @param {?} type
* @return {?}
*/
Reflector.prototype.importUri = function (type) { return this.reflectionCapabilities.importUri(type); };
/**
* @param {?} type
* @return {?}
*/
Reflector.prototype.resourceUri = function (type) { return this.reflectionCapabilities.resourceUri(type); };
/**
* @param {?} name
* @param {?} moduleUrl
* @param {?} members
* @param {?} runtime
* @return {?}
*/
Reflector.prototype.resolveIdentifier = function (name, moduleUrl, members, runtime) {
return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, members, runtime);
};
/**
* @param {?} identifier
* @param {?} name
* @return {?}
*/
Reflector.prototype.resolveEnum = function (identifier, name) {
return this.reflectionCapabilities.resolveEnum(identifier, name);
};
return Reflector;
}(ReflectorReader));
/**
* @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
*/
/**
* The {@link Reflector} used internally in Angular to access metadata
* about symbols.
*/
var reflector = new Reflector(new ReflectionCapabilities());
/**
* @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
*/
/**
* `Dependency` is used by the framework to extend DI.
* This is internal to Angular and should not be used directly.
*/
var ReflectiveDependency = (function () {
/**
* @param {?} key
* @param {?} optional
* @param {?} visibility
*/
function ReflectiveDependency(key, optional, visibility) {
this.key = key;
this.optional = optional;
this.visibility = visibility;
}
/**
* @param {?} key
* @return {?}
*/
ReflectiveDependency.fromKey = function (key) {
return new ReflectiveDependency(key, false, null);
};
return ReflectiveDependency;
}());
var _EMPTY_LIST = [];
var ResolvedReflectiveProvider_ = (function () {
/**
* @param {?} key
* @param {?} resolvedFactories
* @param {?} multiProvider
*/
function ResolvedReflectiveProvider_(key, resolvedFactories, multiProvider) {
this.key = key;
this.resolvedFactories = resolvedFactories;
this.multiProvider = multiProvider;
}
Object.defineProperty(ResolvedReflectiveProvider_.prototype, "resolvedFactory", {
/**
* @return {?}
*/
get: function () { return this.resolvedFactories[0]; },
enumerable: true,
configurable: true
});
return ResolvedReflectiveProvider_;
}());
/**
* An internal resolved representation of a factory function created by resolving {\@link
* Provider}.
* \@experimental
*/
var ResolvedReflectiveFactory = (function () {
/**
* @param {?} factory
* @param {?} dependencies
*/
function ResolvedReflectiveFactory(factory, dependencies) {
this.factory = factory;
this.dependencies = dependencies;
}
return ResolvedReflectiveFactory;
}());
/**
* Resolve a single provider.
* @param {?} provider
* @return {?}
*/
function resolveReflectiveFactory(provider) {
var /** @type {?} */ factoryFn;
var /** @type {?} */ resolvedDeps;
if (provider.useClass) {
var /** @type {?} */ useClass = resolveForwardRef(provider.useClass);
factoryFn = reflector.factory(useClass);
resolvedDeps = _dependenciesFor(useClass);
}
else if (provider.useExisting) {
factoryFn = function (aliasInstance) { return aliasInstance; };
resolvedDeps = [ReflectiveDependency.fromKey(ReflectiveKey.get(provider.useExisting))];
}
else if (provider.useFactory) {
factoryFn = provider.useFactory;
resolvedDeps = constructDependencies(provider.useFactory, provider.deps);
}
else {
factoryFn = function () { return provider.useValue; };
resolvedDeps = _EMPTY_LIST;
}
return new ResolvedReflectiveFactory(factoryFn, resolvedDeps);
}
/**
* Converts the {\@link Provider} into {\@link ResolvedProvider}.
*
* {\@link Injector} internally only uses {\@link ResolvedProvider}, {\@link Provider} contains
* convenience provider syntax.
* @param {?} provider
* @return {?}
*/
function resolveReflectiveProvider(provider) {
return new ResolvedReflectiveProvider_(ReflectiveKey.get(provider.provide), [resolveReflectiveFactory(provider)], provider.multi || false);
}
/**
* Resolve a list of Providers.
* @param {?} providers
* @return {?}
*/
function resolveReflectiveProviders(providers) {
var /** @type {?} */ normalized = _normalizeProviders(providers, []);
var /** @type {?} */ resolved = normalized.map(resolveReflectiveProvider);
var /** @type {?} */ resolvedProviderMap = mergeResolvedReflectiveProviders(resolved, new Map());
return Array.from(resolvedProviderMap.values());
}
/**
* Merges a list of ResolvedProviders into a list where
* each key is contained exactly once and multi providers
* have been merged.
* @param {?} providers
* @param {?} normalizedProvidersMap
* @return {?}
*/
function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
for (var /** @type {?} */ i = 0; i < providers.length; i++) {
var /** @type {?} */ provider = providers[i];
var /** @type {?} */ existing = normalizedProvidersMap.get(provider.key.id);
if (existing) {
if (provider.multiProvider !== existing.multiProvider) {
throw mixingMultiProvidersWithRegularProvidersError(existing, provider);
}
if (provider.multiProvider) {
for (var /** @type {?} */ j = 0; j < provider.resolvedFactories.length; j++) {
existing.resolvedFactories.push(provider.resolvedFactories[j]);
}
}
else {
normalizedProvidersMap.set(provider.key.id, provider);
}
}
else {
var /** @type {?} */ resolvedProvider = void 0;
if (provider.multiProvider) {
resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
}
else {
resolvedProvider = provider;
}
normalizedProvidersMap.set(provider.key.id, resolvedProvider);
}
}
return normalizedProvidersMap;
}
/**
* @param {?} providers
* @param {?} res
* @return {?}
*/
function _normalizeProviders(providers, res) {
providers.forEach(function (b) {
if (b instanceof Type) {
res.push({ provide: b, useClass: b });
}
else if (b && typeof b == 'object' && ((b)).provide !== undefined) {
res.push(/** @type {?} */ (b));
}
else if (b instanceof Array) {
_normalizeProviders(b, res);
}
else {
throw invalidProviderError(b);
}
});
return res;
}
/**
* @param {?} typeOrFunc
* @param {?=} dependencies
* @return {?}
*/
function constructDependencies(typeOrFunc, dependencies) {
if (!dependencies) {
return _dependenciesFor(typeOrFunc);
}
else {
var /** @type {?} */ params_1 = dependencies.map(function (t) { return [t]; });
return dependencies.map(function (t) { return _extractToken(typeOrFunc, t, params_1); });
}
}
/**
* @param {?} typeOrFunc
* @return {?}
*/
function _dependenciesFor(typeOrFunc) {
var /** @type {?} */ params = reflector.parameters(typeOrFunc);
if (!params)
return [];
if (params.some(function (p) { return p == null; })) {
throw noAnnotationError(typeOrFunc, params);
}
return params.map(function (p) { return _extractToken(typeOrFunc, p, params); });
}
/**
* @param {?} typeOrFunc
* @param {?} metadata
* @param {?} params
* @return {?}
*/
function _extractToken(typeOrFunc, metadata, params) {
var /** @type {?} */ token = null;
var /** @type {?} */ optional = false;
if (!Array.isArray(metadata)) {
if (metadata instanceof Inject) {
return _createDependency(metadata['token'], optional, null);
}
else {
return _createDependency(metadata, optional, null);
}
}
var /** @type {?} */ visibility = null;
for (var /** @type {?} */ i = 0; i < metadata.length; ++i) {
var /** @type {?} */ paramMetadata = metadata[i];
if (paramMetadata instanceof Type) {
token = paramMetadata;
}
else if (paramMetadata instanceof Inject) {
token = paramMetadata['token'];
}
else if (paramMetadata instanceof Optional) {
optional = true;
}
else if (paramMetadata instanceof Self || paramMetadata instanceof SkipSelf) {
visibility = paramMetadata;
}
else if (paramMetadata instanceof InjectionToken) {
token = paramMetadata;
}
}
token = resolveForwardRef(token);
if (token != null) {
return _createDependency(token, optional, visibility);
}
else {
throw noAnnotationError(typeOrFunc, params);
}
}
/**
* @param {?} token
* @param {?} optional
* @param {?} visibility
* @return {?}
*/
function _createDependency(token, optional, visibility) {
return new ReflectiveDependency(ReflectiveKey.get(token), optional, visibility);
}
/**
* @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
*/
// Threshold for the dynamic version
var UNDEFINED = new Object();
/**
* A ReflectiveDependency injection container used for instantiating objects and resolving
* dependencies.
*
* An `Injector` is a replacement for a `new` operator, which can automatically resolve the
* constructor dependencies.
*
* In typical use, application code asks for the dependencies in the constructor and they are
* resolved by the `Injector`.
*
* ### Example ([live demo](http://plnkr.co/edit/jzjec0?p=preview))
*
* The following example creates an `Injector` configured to create `Engine` and `Car`.
*
* ```typescript
* \@Injectable()
* class Engine {
* }
*
* \@Injectable()
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
* var car = injector.get(Car);
* expect(car instanceof Car).toBe(true);
* expect(car.engine instanceof Engine).toBe(true);
* ```
*
* Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
* resolve all of the object's dependencies automatically.
*
* \@stable
* @abstract
*/
var ReflectiveInjector = (function () {
function ReflectiveInjector() {
}
/**
* Turns an array of provider definitions into an array of resolved providers.
*
* A resolution is a process of flattening multiple nested arrays and converting individual
* providers into an array of {\@link ResolvedReflectiveProvider}s.
*
* ### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
*
* ```typescript
* \@Injectable()
* class Engine {
* }
*
* \@Injectable()
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var providers = ReflectiveInjector.resolve([Car, [[Engine]]]);
*
* expect(providers.length).toEqual(2);
*
* expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true);
* expect(providers[0].key.displayName).toBe("Car");
* expect(providers[0].dependencies.length).toEqual(1);
* expect(providers[0].factory).toBeDefined();
*
* expect(providers[1].key.displayName).toBe("Engine");
* });
* ```
*
* See {\@link ReflectiveInjector#fromResolvedProviders} for more info.
* @param {?} providers
* @return {?}
*/
ReflectiveInjector.resolve = function (providers) {
return resolveReflectiveProviders(providers);
};
/**
* Resolves an array of providers and creates an injector from those providers.
*
* The passed-in providers can be an array of `Type`, {\@link Provider},
* or a recursive array of more providers.
*
* ### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
*
* ```typescript
* \@Injectable()
* class Engine {
* }
*
* \@Injectable()
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
* expect(injector.get(Car) instanceof Car).toBe(true);
* ```
*
* This function is slower than the corresponding `fromResolvedProviders`
* because it needs to resolve the passed-in providers first.
* See {\@link Injector#resolve} and {\@link Injector#fromResolvedProviders}.
* @param {?} providers
* @param {?=} parent
* @return {?}
*/
ReflectiveInjector.resolveAndCreate = function (providers, parent) {
var /** @type {?} */ ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
return ReflectiveInjector.fromResolvedProviders(ResolvedReflectiveProviders, parent);
};
/**
* Creates an injector from previously resolved providers.
*
* This API is the recommended way to construct injectors in performance-sensitive parts.
*
* ### Example ([live demo](http://plnkr.co/edit/KrSMci?p=preview))
*
* ```typescript
* \@Injectable()
* class Engine {
* }
*
* \@Injectable()
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var providers = ReflectiveInjector.resolve([Car, Engine]);
* var injector = ReflectiveInjector.fromResolvedProviders(providers);
* expect(injector.get(Car) instanceof Car).toBe(true);
* ```
* \@experimental
* @param {?} providers
* @param {?=} parent
* @return {?}
*/
ReflectiveInjector.fromResolvedProviders = function (providers, parent) {
return new ReflectiveInjector_(providers, parent);
};
/**
* Parent of this injector.
*
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
* -->
*
* ### Example ([live demo](http://plnkr.co/edit/eosMGo?p=preview))
*
* ```typescript
* var parent = ReflectiveInjector.resolveAndCreate([]);
* var child = parent.resolveAndCreateChild([]);
* expect(child.parent).toBe(parent);
* ```
* @abstract
* @return {?}
*/
ReflectiveInjector.prototype.parent = function () { };
/**
* Resolves an array of providers and creates a child injector from those providers.
*
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
* -->
*
* The passed-in providers can be an array of `Type`, {\@link Provider},
* or a recursive array of more providers.
*
* ### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
*
* ```typescript
* class ParentProvider {}
* class ChildProvider {}
*
* var parent = ReflectiveInjector.resolveAndCreate([ParentProvider]);
* var child = parent.resolveAndCreateChild([ChildProvider]);
*
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
* ```
*
* This function is slower than the corresponding `createChildFromResolved`
* because it needs to resolve the passed-in providers first.
* See {\@link Injector#resolve} and {\@link Injector#createChildFromResolved}.
* @abstract
* @param {?} providers
* @return {?}
*/
ReflectiveInjector.prototype.resolveAndCreateChild = function (providers) { };
/**
* Creates a child injector from previously resolved providers.
*
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
* -->
*
* This API is the recommended way to construct injectors in performance-sensitive parts.
*
* ### Example ([live demo](http://plnkr.co/edit/VhyfjN?p=preview))
*
* ```typescript
* class ParentProvider {}
* class ChildProvider {}
*
* var parentProviders = ReflectiveInjector.resolve([ParentProvider]);
* var childProviders = ReflectiveInjector.resolve([ChildProvider]);
*
* var parent = ReflectiveInjector.fromResolvedProviders(parentProviders);
* var child = parent.createChildFromResolved(childProviders);
*
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
* ```
* @abstract
* @param {?} providers
* @return {?}
*/
ReflectiveInjector.prototype.createChildFromResolved = function (providers) { };
/**
* Resolves a provider and instantiates an object in the context of the injector.
*
* The created object does not get cached by the injector.
*
* ### Example ([live demo](http://plnkr.co/edit/yvVXoB?p=preview))
*
* ```typescript
* \@Injectable()
* class Engine {
* }
*
* \@Injectable()
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var injector = ReflectiveInjector.resolveAndCreate([Engine]);
*
* var car = injector.resolveAndInstantiate(Car);
* expect(car.engine).toBe(injector.get(Engine));
* expect(car).not.toBe(injector.resolveAndInstantiate(Car));
* ```
* @abstract
* @param {?} provider
* @return {?}
*/
ReflectiveInjector.prototype.resolveAndInstantiate = function (provider) { };
/**
* Instantiates an object using a resolved provider in the context of the injector.
*
* The created object does not get cached by the injector.
*
* ### Example ([live demo](http://plnkr.co/edit/ptCImQ?p=preview))
*
* ```typescript
* \@Injectable()
* class Engine {
* }
*
* \@Injectable()
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var injector = ReflectiveInjector.resolveAndCreate([Engine]);
* var carProvider = ReflectiveInjector.resolve([Car])[0];
* var car = injector.instantiateResolved(carProvider);
* expect(car.engine).toBe(injector.get(Engine));
* expect(car).not.toBe(injector.instantiateResolved(carProvider));
* ```
* @abstract
* @param {?} provider
* @return {?}
*/
ReflectiveInjector.prototype.instantiateResolved = function (provider) { };
/**
* @abstract
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
ReflectiveInjector.prototype.get = function (token, notFoundValue) { };
return ReflectiveInjector;
}());
var ReflectiveInjector_ = (function () {
/**
* Private
* @param {?} _providers
* @param {?=} _parent
*/
function ReflectiveInjector_(_providers, _parent) {
/**
* \@internal
*/
this._constructionCounter = 0;
this._providers = _providers;
this._parent = _parent || null;
var len = _providers.length;
this.keyIds = new Array(len);
this.objs = new Array(len);
for (var i = 0; i < len; i++) {
this.keyIds[i] = _providers[i].key.id;
this.objs[i] = UNDEFINED;
}
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
ReflectiveInjector_.prototype.get = function (token, notFoundValue) {
if (notFoundValue === void 0) { notFoundValue = THROW_IF_NOT_FOUND; }
return this._getByKey(ReflectiveKey.get(token), null, notFoundValue);
};
Object.defineProperty(ReflectiveInjector_.prototype, "parent", {
/**
* @return {?}
*/
get: function () { return this._parent; },
enumerable: true,
configurable: true
});
/**
* @param {?} providers
* @return {?}
*/
ReflectiveInjector_.prototype.resolveAndCreateChild = function (providers) {
var /** @type {?} */ ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
return this.createChildFromResolved(ResolvedReflectiveProviders);
};
/**
* @param {?} providers
* @return {?}
*/
ReflectiveInjector_.prototype.createChildFromResolved = function (providers) {
var /** @type {?} */ inj = new ReflectiveInjector_(providers);
inj._parent = this;
return inj;
};
/**
* @param {?} provider
* @return {?}
*/
ReflectiveInjector_.prototype.resolveAndInstantiate = function (provider) {
return this.instantiateResolved(ReflectiveInjector.resolve([provider])[0]);
};
/**
* @param {?} provider
* @return {?}
*/
ReflectiveInjector_.prototype.instantiateResolved = function (provider) {
return this._instantiateProvider(provider);
};
/**
* @param {?} index
* @return {?}
*/
ReflectiveInjector_.prototype.getProviderAtIndex = function (index) {
if (index < 0 || index >= this._providers.length) {
throw outOfBoundsError(index);
}
return this._providers[index];
};
/**
* \@internal
* @param {?} provider
* @return {?}
*/
ReflectiveInjector_.prototype._new = function (provider) {
if (this._constructionCounter++ > this._getMaxNumberOfObjects()) {
throw cyclicDependencyError(this, provider.key);
}
return this._instantiateProvider(provider);
};
/**
* @return {?}
*/
ReflectiveInjector_.prototype._getMaxNumberOfObjects = function () { return this.objs.length; };
/**
* @param {?} provider
* @return {?}
*/
ReflectiveInjector_.prototype._instantiateProvider = function (provider) {
if (provider.multiProvider) {
var /** @type {?} */ res = new Array(provider.resolvedFactories.length);
for (var /** @type {?} */ i = 0; i < provider.resolvedFactories.length; ++i) {
res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
}
return res;
}
else {
return this._instantiate(provider, provider.resolvedFactories[0]);
}
};
/**
* @param {?} provider
* @param {?} ResolvedReflectiveFactory
* @return {?}
*/
ReflectiveInjector_.prototype._instantiate = function (provider, ResolvedReflectiveFactory$$1) {
var _this = this;
var /** @type {?} */ factory = ResolvedReflectiveFactory$$1.factory;
var /** @type {?} */ deps;
try {
deps =
ResolvedReflectiveFactory$$1.dependencies.map(function (dep) { return _this._getByReflectiveDependency(dep); });
}
catch (e) {
if (e.addKey) {
e.addKey(this, provider.key);
}
throw e;
}
var /** @type {?} */ obj;
try {
obj = factory.apply(void 0, deps);
}
catch (e) {
throw instantiationError(this, e, e.stack, provider.key);
}
return obj;
};
/**
* @param {?} dep
* @return {?}
*/
ReflectiveInjector_.prototype._getByReflectiveDependency = function (dep) {
return this._getByKey(dep.key, dep.visibility, dep.optional ? null : THROW_IF_NOT_FOUND);
};
/**
* @param {?} key
* @param {?} visibility
* @param {?} notFoundValue
* @return {?}
*/
ReflectiveInjector_.prototype._getByKey = function (key, visibility, notFoundValue) {
if (key === INJECTOR_KEY) {
return this;
}
if (visibility instanceof Self) {
return this._getByKeySelf(key, notFoundValue);
}
else {
return this._getByKeyDefault(key, notFoundValue, visibility);
}
};
/**
* @param {?} keyId
* @return {?}
*/
ReflectiveInjector_.prototype._getObjByKeyId = function (keyId) {
for (var /** @type {?} */ i = 0; i < this.keyIds.length; i++) {
if (this.keyIds[i] === keyId) {
if (this.objs[i] === UNDEFINED) {
this.objs[i] = this._new(this._providers[i]);
}
return this.objs[i];
}
}
return UNDEFINED;
};
/**
* \@internal
* @param {?} key
* @param {?} notFoundValue
* @return {?}
*/
ReflectiveInjector_.prototype._throwOrNull = function (key, notFoundValue) {
if (notFoundValue !== THROW_IF_NOT_FOUND) {
return notFoundValue;
}
else {
throw noProviderError(this, key);
}
};
/**
* \@internal
* @param {?} key
* @param {?} notFoundValue
* @return {?}
*/
ReflectiveInjector_.prototype._getByKeySelf = function (key, notFoundValue) {
var /** @type {?} */ obj = this._getObjByKeyId(key.id);
return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, notFoundValue);
};
/**
* \@internal
* @param {?} key
* @param {?} notFoundValue
* @param {?} visibility
* @return {?}
*/
ReflectiveInjector_.prototype._getByKeyDefault = function (key, notFoundValue, visibility) {
var /** @type {?} */ inj;
if (visibility instanceof SkipSelf) {
inj = this._parent;
}
else {
inj = this;
}
while (inj instanceof ReflectiveInjector_) {
var /** @type {?} */ inj_ = (inj);
var /** @type {?} */ obj = inj_._getObjByKeyId(key.id);
if (obj !== UNDEFINED)
return obj;
inj = inj_._parent;
}
if (inj !== null) {
return inj.get(key.token, notFoundValue);
}
else {
return this._throwOrNull(key, notFoundValue);
}
};
Object.defineProperty(ReflectiveInjector_.prototype, "displayName", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ providers = _mapProviders(this, function (b) { return ' "' + b.key.displayName + '" '; })
.join(', ');
return "ReflectiveInjector(providers: [" + providers + "])";
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
ReflectiveInjector_.prototype.toString = function () { return this.displayName; };
return ReflectiveInjector_;
}());
var INJECTOR_KEY = ReflectiveKey.get(Injector);
/**
* @param {?} injector
* @param {?} fn
* @return {?}
*/
function _mapProviders(injector, fn) {
var /** @type {?} */ res = new Array(injector._providers.length);
for (var /** @type {?} */ i = 0; i < injector._providers.length; ++i) {
res[i] = fn(injector.getProviderAtIndex(i));
}
return res;
}
/**
* @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
*/
/**
* @module
* @description
* The `di` module provides dependency injection container services.
*/
/**
* @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
*/
/**
* Determine if the argument is shaped like a Promise
* @param {?} obj
* @return {?}
*/
function isPromise(obj) {
// allow any Promise/A+ compliant thenable.
// It's up to the caller to ensure that obj.then conforms to the spec
return !!obj && typeof obj.then === 'function';
}
/**
* Determine if the argument is an Observable
* @param {?} obj
* @return {?}
*/
function isObservable(obj) {
// TODO use Symbol.observable when https://github.com/ReactiveX/rxjs/issues/2415 will be resolved
return !!obj && typeof obj.subscribe === 'function';
}
/**
* @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
*/
/**
* A function that will be executed when an application is initialized.
* \@experimental
*/
var APP_INITIALIZER = new InjectionToken('Application Initializer');
/**
* A class that reflects the state of running {\@link APP_INITIALIZER}s.
*
* \@experimental
*/
var ApplicationInitStatus = (function () {
/**
* @param {?} appInits
*/
function ApplicationInitStatus(appInits) {
var _this = this;
this._done = false;
var asyncInitPromises = [];
if (appInits) {
for (var i = 0; i < appInits.length; i++) {
var initResult = appInits[i]();
if (isPromise(initResult)) {
asyncInitPromises.push(initResult);
}
}
}
this._donePromise = Promise.all(asyncInitPromises).then(function () { _this._done = true; });
if (asyncInitPromises.length === 0) {
this._done = true;
}
}
Object.defineProperty(ApplicationInitStatus.prototype, "done", {
/**
* @return {?}
*/
get: function () { return this._done; },
enumerable: true,
configurable: true
});
Object.defineProperty(ApplicationInitStatus.prototype, "donePromise", {
/**
* @return {?}
*/
get: function () { return this._donePromise; },
enumerable: true,
configurable: true
});
return ApplicationInitStatus;
}());
ApplicationInitStatus.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
ApplicationInitStatus.ctorParameters = function () { return [
{ type: Array, decorators: [{ type: Inject, args: [APP_INITIALIZER,] }, { type: Optional },] },
]; };
/**
* @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
*/
/**
* A DI Token representing a unique string id assigned to the application by Angular and used
* primarily for prefixing application attributes and CSS styles when
* {\@link ViewEncapsulation#Emulated} is being used.
*
* If you need to avoid randomly generated value to be used as an application id, you can provide
* a custom value via a DI provider <!-- TODO: provider --> configuring the root {\@link Injector}
* using this token.
* \@experimental
*/
var APP_ID = new InjectionToken('AppId');
/**
* @return {?}
*/
function _appIdRandomProviderFactory() {
return "" + _randomChar() + _randomChar() + _randomChar();
}
/**
* Providers that will generate a random APP_ID_TOKEN.
* \@experimental
*/
var APP_ID_RANDOM_PROVIDER = {
provide: APP_ID,
useFactory: _appIdRandomProviderFactory,
deps: [],
};
/**
* @return {?}
*/
function _randomChar() {
return String.fromCharCode(97 + Math.floor(Math.random() * 25));
}
/**
* A function that will be executed when a platform is initialized.
* \@experimental
*/
var PLATFORM_INITIALIZER = new InjectionToken('Platform Initializer');
/**
* A token that indicates an opaque platform id.
* \@experimental
*/
var PLATFORM_ID = new InjectionToken('Platform ID');
/**
* All callbacks provided via this token will be called for every component that is bootstrapped.
* Signature of the callback:
*
* `(componentRef: ComponentRef) => void`.
*
* \@experimental
*/
var APP_BOOTSTRAP_LISTENER = new InjectionToken('appBootstrapListener');
/**
* A token which indicates the root directory of the application
* \@experimental
*/
var PACKAGE_ROOT_URL = new InjectionToken('Application Packages Root URL');
/**
* @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
*/
var Console = (function () {
function Console() {
}
/**
* @param {?} message
* @return {?}
*/
Console.prototype.log = function (message) {
// tslint:disable-next-line:no-console
console.log(message);
};
/**
* @param {?} message
* @return {?}
*/
Console.prototype.warn = function (message) {
// tslint:disable-next-line:no-console
console.warn(message);
};
return Console;
}());
Console.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
Console.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* Combination of NgModuleFactory and ComponentFactorys.
*
* \@experimental
*/
var ModuleWithComponentFactories = (function () {
/**
* @param {?} ngModuleFactory
* @param {?} componentFactories
*/
function ModuleWithComponentFactories(ngModuleFactory, componentFactories) {
this.ngModuleFactory = ngModuleFactory;
this.componentFactories = componentFactories;
}
return ModuleWithComponentFactories;
}());
/**
* @return {?}
*/
function _throwError() {
throw new Error("Runtime compiler is not loaded");
}
/**
* Low-level service for running the angular compiler during runtime
* to create {\@link ComponentFactory}s, which
* can later be used to create and render a Component instance.
*
* Each `\@NgModule` provides an own `Compiler` to its injector,
* that will use the directives/pipes of the ng module for compilation
* of components.
* \@stable
*/
var Compiler = (function () {
function Compiler() {
}
/**
* Compiles the given NgModule and all of its components. All templates of the components listed
* in `entryComponents` have to be inlined.
* @template T
* @param {?} moduleType
* @return {?}
*/
Compiler.prototype.compileModuleSync = function (moduleType) { throw _throwError(); };
/**
* Compiles the given NgModule and all of its components
* @template T
* @param {?} moduleType
* @return {?}
*/
Compiler.prototype.compileModuleAsync = function (moduleType) { throw _throwError(); };
/**
* Same as {\@link #compileModuleSync} but also creates ComponentFactories for all components.
* @template T
* @param {?} moduleType
* @return {?}
*/
Compiler.prototype.compileModuleAndAllComponentsSync = function (moduleType) {
throw _throwError();
};
/**
* Same as {\@link #compileModuleAsync} but also creates ComponentFactories for all components.
* @template T
* @param {?} moduleType
* @return {?}
*/
Compiler.prototype.compileModuleAndAllComponentsAsync = function (moduleType) {
throw _throwError();
};
/**
* Exposes the CSS-style selectors that have been used in `ngContent` directives within
* the template of the given component.
* This is used by the `upgrade` library to compile the appropriate transclude content
* in the AngularJS wrapper component.
*
* @deprecated since v4. Use ComponentFactory.ngContentSelectors instead.
* @param {?} component
* @return {?}
*/
Compiler.prototype.getNgContentSelectors = function (component) { throw _throwError(); };
/**
* Clears all caches.
* @return {?}
*/
Compiler.prototype.clearCache = function () { };
/**
* Clears the cache for the given component/ngModule.
* @param {?} type
* @return {?}
*/
Compiler.prototype.clearCacheFor = function (type) { };
return Compiler;
}());
Compiler.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
Compiler.ctorParameters = function () { return []; };
/**
* Token to provide CompilerOptions in the platform injector.
*
* \@experimental
*/
var COMPILER_OPTIONS = new InjectionToken('compilerOptions');
/**
* A factory for creating a Compiler
*
* \@experimental
* @abstract
*/
var CompilerFactory = (function () {
function CompilerFactory() {
}
/**
* @abstract
* @param {?=} options
* @return {?}
*/
CompilerFactory.prototype.createCompiler = function (options) { };
return CompilerFactory;
}());
/**
* @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
*/
/**
* Represents an instance of a Component created via a {\@link ComponentFactory}.
*
* `ComponentRef` provides access to the Component Instance as well other objects related to this
* Component Instance and allows you to destroy the Component Instance via the {\@link #destroy}
* method.
* \@stable
* @abstract
*/
var ComponentRef = (function () {
function ComponentRef() {
}
/**
* Location of the Host Element of this Component Instance.
* @abstract
* @return {?}
*/
ComponentRef.prototype.location = function () { };
/**
* The injector on which the component instance exists.
* @abstract
* @return {?}
*/
ComponentRef.prototype.injector = function () { };
/**
* The instance of the Component.
* @abstract
* @return {?}
*/
ComponentRef.prototype.instance = function () { };
/**
* The {\@link ViewRef} of the Host View of this Component instance.
* @abstract
* @return {?}
*/
ComponentRef.prototype.hostView = function () { };
/**
* The {\@link ChangeDetectorRef} of the Component instance.
* @abstract
* @return {?}
*/
ComponentRef.prototype.changeDetectorRef = function () { };
/**
* The component type.
* @abstract
* @return {?}
*/
ComponentRef.prototype.componentType = function () { };
/**
* Destroys the component instance and all of the data structures associated with it.
* @abstract
* @return {?}
*/
ComponentRef.prototype.destroy = function () { };
/**
* Allows to register a callback that will be called when the component is destroyed.
* @abstract
* @param {?} callback
* @return {?}
*/
ComponentRef.prototype.onDestroy = function (callback) { };
return ComponentRef;
}());
/**
* \@stable
* @abstract
*/
var ComponentFactory = (function () {
function ComponentFactory() {
}
/**
* @abstract
* @return {?}
*/
ComponentFactory.prototype.selector = function () { };
/**
* @abstract
* @return {?}
*/
ComponentFactory.prototype.componentType = function () { };
/**
* selector for all <ng-content> elements in the component.
* @abstract
* @return {?}
*/
ComponentFactory.prototype.ngContentSelectors = function () { };
/**
* the inputs of the component.
* @abstract
* @return {?}
*/
ComponentFactory.prototype.inputs = function () { };
/**
* the outputs of the component.
* @abstract
* @return {?}
*/
ComponentFactory.prototype.outputs = function () { };
/**
* Creates a new component.
* @abstract
* @param {?} injector
* @param {?=} projectableNodes
* @param {?=} rootSelectorOrNode
* @param {?=} ngModule
* @return {?}
*/
ComponentFactory.prototype.create = function (injector, projectableNodes, rootSelectorOrNode, ngModule) { };
return ComponentFactory;
}());
/**
* @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
*/
/**
* @param {?} component
* @return {?}
*/
function noComponentFactoryError(component) {
var /** @type {?} */ error = Error("No component factory found for " + stringify(component) + ". Did you add it to @NgModule.entryComponents?");
((error))[ERROR_COMPONENT] = component;
return error;
}
var ERROR_COMPONENT = 'ngComponent';
/**
* @param {?} error
* @return {?}
*/
var _NullComponentFactoryResolver = (function () {
function _NullComponentFactoryResolver() {
}
/**
* @template T
* @param {?} component
* @return {?}
*/
_NullComponentFactoryResolver.prototype.resolveComponentFactory = function (component) {
throw noComponentFactoryError(component);
};
return _NullComponentFactoryResolver;
}());
/**
* \@stable
* @abstract
*/
var ComponentFactoryResolver = (function () {
function ComponentFactoryResolver() {
}
/**
* @abstract
* @template T
* @param {?} component
* @return {?}
*/
ComponentFactoryResolver.prototype.resolveComponentFactory = function (component) { };
return ComponentFactoryResolver;
}());
ComponentFactoryResolver.NULL = new _NullComponentFactoryResolver();
var CodegenComponentFactoryResolver = (function () {
/**
* @param {?} factories
* @param {?} _parent
* @param {?} _ngModule
*/
function CodegenComponentFactoryResolver(factories, _parent, _ngModule) {
this._parent = _parent;
this._ngModule = _ngModule;
this._factories = new Map();
for (var i = 0; i < factories.length; i++) {
var factory = factories[i];
this._factories.set(factory.componentType, factory);
}
}
/**
* @template T
* @param {?} component
* @return {?}
*/
CodegenComponentFactoryResolver.prototype.resolveComponentFactory = function (component) {
var /** @type {?} */ factory = this._factories.get(component) || this._parent.resolveComponentFactory(component);
return new ComponentFactoryBoundToModule(factory, this._ngModule);
};
return CodegenComponentFactoryResolver;
}());
var ComponentFactoryBoundToModule = (function (_super) {
__extends(ComponentFactoryBoundToModule, _super);
/**
* @param {?} factory
* @param {?} ngModule
*/
function ComponentFactoryBoundToModule(factory, ngModule) {
var _this = _super.call(this) || this;
_this.factory = factory;
_this.ngModule = ngModule;
return _this;
}
Object.defineProperty(ComponentFactoryBoundToModule.prototype, "selector", {
/**
* @return {?}
*/
get: function () { return this.factory.selector; },
enumerable: true,
configurable: true
});
Object.defineProperty(ComponentFactoryBoundToModule.prototype, "componentType", {
/**
* @return {?}
*/
get: function () { return this.factory.componentType; },
enumerable: true,
configurable: true
});
Object.defineProperty(ComponentFactoryBoundToModule.prototype, "ngContentSelectors", {
/**
* @return {?}
*/
get: function () { return this.factory.ngContentSelectors; },
enumerable: true,
configurable: true
});
Object.defineProperty(ComponentFactoryBoundToModule.prototype, "inputs", {
/**
* @return {?}
*/
get: function () { return this.factory.inputs; },
enumerable: true,
configurable: true
});
Object.defineProperty(ComponentFactoryBoundToModule.prototype, "outputs", {
/**
* @return {?}
*/
get: function () { return this.factory.outputs; },
enumerable: true,
configurable: true
});
/**
* @param {?} injector
* @param {?=} projectableNodes
* @param {?=} rootSelectorOrNode
* @param {?=} ngModule
* @return {?}
*/
ComponentFactoryBoundToModule.prototype.create = function (injector, projectableNodes, rootSelectorOrNode, ngModule) {
return this.factory.create(injector, projectableNodes, rootSelectorOrNode, ngModule || this.ngModule);
};
return ComponentFactoryBoundToModule;
}(ComponentFactory));
/**
* @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
*/
/**
* Represents an instance of an NgModule created via a {\@link NgModuleFactory}.
*
* `NgModuleRef` provides access to the NgModule Instance as well other objects related to this
* NgModule Instance.
*
* \@stable
* @abstract
*/
var NgModuleRef = (function () {
function NgModuleRef() {
}
/**
* The injector that contains all of the providers of the NgModule.
* @abstract
* @return {?}
*/
NgModuleRef.prototype.injector = function () { };
/**
* The ComponentFactoryResolver to get hold of the ComponentFactories
* declared in the `entryComponents` property of the module.
* @abstract
* @return {?}
*/
NgModuleRef.prototype.componentFactoryResolver = function () { };
/**
* The NgModule instance.
* @abstract
* @return {?}
*/
NgModuleRef.prototype.instance = function () { };
/**
* Destroys the module instance and all of the data structures associated with it.
* @abstract
* @return {?}
*/
NgModuleRef.prototype.destroy = function () { };
/**
* Allows to register a callback that will be called when the module is destroyed.
* @abstract
* @param {?} callback
* @return {?}
*/
NgModuleRef.prototype.onDestroy = function (callback) { };
return NgModuleRef;
}());
/**
* \@experimental
*/
var NgModuleFactory = (function () {
/**
* @param {?} _injectorClass
* @param {?} _moduleType
*/
function NgModuleFactory(_injectorClass, _moduleType) {
this._injectorClass = _injectorClass;
this._moduleType = _moduleType;
}
Object.defineProperty(NgModuleFactory.prototype, "moduleType", {
/**
* @return {?}
*/
get: function () { return this._moduleType; },
enumerable: true,
configurable: true
});
/**
* @param {?} parentInjector
* @return {?}
*/
NgModuleFactory.prototype.create = function (parentInjector) {
var /** @type {?} */ instance = new this._injectorClass(parentInjector || Injector.NULL);
instance.create();
return instance;
};
return NgModuleFactory;
}());
var _UNDEFINED = new Object();
/**
* @abstract
*/
var NgModuleInjector = (function () {
/**
* @param {?} parent
* @param {?} factories
* @param {?} bootstrapFactories
*/
function NgModuleInjector(parent, factories, bootstrapFactories) {
var _this = this;
this.parent = parent;
this._destroyListeners = [];
this._destroyed = false;
this.bootstrapFactories =
bootstrapFactories.map(function (f) { return new ComponentFactoryBoundToModule(f, _this); });
this._cmpFactoryResolver = new CodegenComponentFactoryResolver(factories, parent.get(ComponentFactoryResolver, ComponentFactoryResolver.NULL), this);
}
/**
* @return {?}
*/
NgModuleInjector.prototype.create = function () { this.instance = this.createInternal(); };
/**
* @abstract
* @return {?}
*/
NgModuleInjector.prototype.createInternal = function () { };
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
NgModuleInjector.prototype.get = function (token, notFoundValue) {
if (notFoundValue === void 0) { notFoundValue = THROW_IF_NOT_FOUND; }
if (token === Injector || token === NgModuleRef) {
return this;
}
if (token === ComponentFactoryResolver) {
return this._cmpFactoryResolver;
}
var /** @type {?} */ result = this.getInternal(token, _UNDEFINED);
return result === _UNDEFINED ? this.parent.get(token, notFoundValue) : result;
};
/**
* @abstract
* @param {?} token
* @param {?} notFoundValue
* @return {?}
*/
NgModuleInjector.prototype.getInternal = function (token, notFoundValue) { };
Object.defineProperty(NgModuleInjector.prototype, "injector", {
/**
* @return {?}
*/
get: function () { return this; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModuleInjector.prototype, "componentFactoryResolver", {
/**
* @return {?}
*/
get: function () { return this._cmpFactoryResolver; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
NgModuleInjector.prototype.destroy = function () {
if (this._destroyed) {
throw new Error("The ng module " + stringify(this.instance.constructor) + " has already been destroyed.");
}
this._destroyed = true;
this.destroyInternal();
this._destroyListeners.forEach(function (listener) { return listener(); });
};
/**
* @param {?} callback
* @return {?}
*/
NgModuleInjector.prototype.onDestroy = function (callback) { this._destroyListeners.push(callback); };
/**
* @abstract
* @return {?}
*/
NgModuleInjector.prototype.destroyInternal = function () { };
return NgModuleInjector;
}());
/**
* @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
*/
var trace;
var events;
/**
* @return {?}
*/
function detectWTF() {
var /** @type {?} */ wtf = ((_global) /** TODO #9100 */)['wtf'];
if (wtf) {
trace = wtf['trace'];
if (trace) {
events = trace['events'];
return true;
}
}
return false;
}
/**
* @param {?} signature
* @param {?=} flags
* @return {?}
*/
function createScope$1(signature, flags) {
if (flags === void 0) { flags = null; }
return events.createScope(signature, flags);
}
/**
* @template T
* @param {?} scope
* @param {?=} returnValue
* @return {?}
*/
function leave(scope, returnValue) {
trace.leaveScope(scope, returnValue);
return returnValue;
}
/**
* @param {?} rangeType
* @param {?} action
* @return {?}
*/
function startTimeRange(rangeType, action) {
return trace.beginTimeRange(rangeType, action);
}
/**
* @param {?} range
* @return {?}
*/
function endTimeRange(range) {
trace.endTimeRange(range);
}
/**
* @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
*/
/**
* True if WTF is enabled.
*/
var wtfEnabled = detectWTF();
/**
* @param {?=} arg0
* @param {?=} arg1
* @return {?}
*/
function noopScope(arg0, arg1) {
return null;
}
/**
* Create trace scope.
*
* Scopes must be strictly nested and are analogous to stack frames, but
* do not have to follow the stack frames. Instead it is recommended that they follow logical
* nesting. You may want to use
* [Event
* Signatures](http://google.github.io/tracing-framework/instrumenting-code.html#custom-events)
* as they are defined in WTF.
*
* Used to mark scope entry. The return value is used to leave the scope.
*
* var myScope = wtfCreateScope('MyClass#myMethod(ascii someVal)');
*
* someMethod() {
* var s = myScope('Foo'); // 'Foo' gets stored in tracing UI
* // DO SOME WORK HERE
* return wtfLeave(s, 123); // Return value 123
* }
*
* Note, adding try-finally block around the work to ensure that `wtfLeave` gets called can
* negatively impact the performance of your application. For this reason we recommend that
* you don't add them to ensure that `wtfLeave` gets called. In production `wtfLeave` is a noop and
* so try-finally block has no value. When debugging perf issues, skipping `wtfLeave`, do to
* exception, will produce incorrect trace, but presence of exception signifies logic error which
* needs to be fixed before the app should be profiled. Add try-finally only when you expect that
* an exception is expected during normal execution while profiling.
*
* \@experimental
*/
var wtfCreateScope = wtfEnabled ? createScope$1 : function (signature, flags) { return noopScope; };
/**
* Used to mark end of Scope.
*
* - `scope` to end.
* - `returnValue` (optional) to be passed to the WTF.
*
* Returns the `returnValue for easy chaining.
* \@experimental
*/
var wtfLeave = wtfEnabled ? leave : function (s, r) { return r; };
/**
* Used to mark Async start. Async are similar to scope but they don't have to be strictly nested.
* The return value is used in the call to [endAsync]. Async ranges only work if WTF has been
* enabled.
*
* someMethod() {
* var s = wtfStartTimeRange('HTTP:GET', 'some.url');
* var future = new Future.delay(5).then((_) {
* wtfEndTimeRange(s);
* });
* }
* \@experimental
*/
var wtfStartTimeRange = wtfEnabled ? startTimeRange : function (rangeType, action) { return null; };
/**
* Ends a async time range operation.
* [range] is the return value from [wtfStartTimeRange] Async ranges only work if WTF has been
* enabled.
* \@experimental
*/
var wtfEndTimeRange = wtfEnabled ? endTimeRange : function (r) { return null; };
/**
* @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
*/
/**
* Use by directives and components to emit custom Events.
*
* ### Examples
*
* In the following example, `Zippy` alternatively emits `open` and `close` events when its
* title gets clicked:
*
* ```
* \@Component({
* selector: 'zippy',
* template: `
* <div class="zippy">
* <div (click)="toggle()">Toggle</div>
* <div [hidden]="!visible">
* <ng-content></ng-content>
* </div>
* </div>`})
* export class Zippy {
* visible: boolean = true;
* \@Output() open: EventEmitter<any> = new EventEmitter();
* \@Output() close: EventEmitter<any> = new EventEmitter();
*
* toggle() {
* this.visible = !this.visible;
* if (this.visible) {
* this.open.emit(null);
* } else {
* this.close.emit(null);
* }
* }
* }
* ```
*
* The events payload can be accessed by the parameter `$event` on the components output event
* handler:
*
* ```
* <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy>
* ```
*
* Uses Rx.Observable but provides an adapter to make it work as specified here:
* https://github.com/jhusain/observable-spec
*
* Once a reference implementation of the spec is available, switch to it.
* \@stable
*/
var EventEmitter = (function (_super) {
__extends(EventEmitter, _super);
/**
* Creates an instance of [EventEmitter], which depending on [isAsync],
* delivers events synchronously or asynchronously.
* @param {?=} isAsync
*/
function EventEmitter(isAsync) {
if (isAsync === void 0) { isAsync = false; }
var _this = _super.call(this) || this;
_this.__isAsync = isAsync;
return _this;
}
/**
* @param {?=} value
* @return {?}
*/
EventEmitter.prototype.emit = function (value) { _super.prototype.next.call(this, value); };
/**
* @param {?=} generatorOrNext
* @param {?=} error
* @param {?=} complete
* @return {?}
*/
EventEmitter.prototype.subscribe = function (generatorOrNext, error, complete) {
var /** @type {?} */ schedulerFn;
var /** @type {?} */ errorFn = function (err) { return null; };
var /** @type {?} */ completeFn = function () { return null; };
if (generatorOrNext && typeof generatorOrNext === 'object') {
schedulerFn = this.__isAsync ? function (value) {
setTimeout(function () { return generatorOrNext.next(value); });
} : function (value) { generatorOrNext.next(value); };
if (generatorOrNext.error) {
errorFn = this.__isAsync ? function (err) { setTimeout(function () { return generatorOrNext.error(err); }); } :
function (err) { generatorOrNext.error(err); };
}
if (generatorOrNext.complete) {
completeFn = this.__isAsync ? function () { setTimeout(function () { return generatorOrNext.complete(); }); } :
function () { generatorOrNext.complete(); };
}
}
else {
schedulerFn = this.__isAsync ? function (value) { setTimeout(function () { return generatorOrNext(value); }); } :
function (value) { generatorOrNext(value); };
if (error) {
errorFn =
this.__isAsync ? function (err) { setTimeout(function () { return error(err); }); } : function (err) { error(err); };
}
if (complete) {
completeFn =
this.__isAsync ? function () { setTimeout(function () { return complete(); }); } : function () { complete(); };
}
}
return _super.prototype.subscribe.call(this, schedulerFn, errorFn, completeFn);
};
return EventEmitter;
}(__WEBPACK_IMPORTED_MODULE_3_rxjs_Subject__["Subject"]));
/**
* @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
*/
/**
* An injectable service for executing work inside or outside of the Angular zone.
*
* The most common use of this service is to optimize performance when starting a work consisting of
* one or more asynchronous tasks that don't require UI updates or error handling to be handled by
* Angular. Such tasks can be kicked off via {\@link #runOutsideAngular} and if needed, these tasks
* can reenter the Angular zone via {\@link #run}.
*
* <!-- TODO: add/fix links to:
* - docs explaining zones and the use of zones in Angular and change-detection
* - link to runOutsideAngular/run (throughout this file!)
* -->
*
* ### Example
*
* ```
* import {Component, NgZone} from '\@angular/core';
* import {NgIf} from '\@angular/common';
*
* \@Component({
* selector: 'ng-zone-demo'.
* template: `
* <h2>Demo: NgZone</h2>
*
* <p>Progress: {{progress}}%</p>
* <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
*
* <button (click)="processWithinAngularZone()">Process within Angular zone</button>
* <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
* `,
* })
* export class NgZoneDemo {
* progress: number = 0;
* label: string;
*
* constructor(private _ngZone: NgZone) {}
*
* // Loop inside the Angular zone
* // so the UI DOES refresh after each setTimeout cycle
* processWithinAngularZone() {
* this.label = 'inside';
* this.progress = 0;
* this._increaseProgress(() => console.log('Inside Done!'));
* }
*
* // Loop outside of the Angular zone
* // so the UI DOES NOT refresh after each setTimeout cycle
* processOutsideOfAngularZone() {
* this.label = 'outside';
* this.progress = 0;
* this._ngZone.runOutsideAngular(() => {
* this._increaseProgress(() => {
* // reenter the Angular zone and display done
* this._ngZone.run(() => {console.log('Outside Done!') });
* }}));
* }
*
* _increaseProgress(doneCallback: () => void) {
* this.progress += 1;
* console.log(`Current progress: ${this.progress}%`);
*
* if (this.progress < 100) {
* window.setTimeout(() => this._increaseProgress(doneCallback)), 10)
* } else {
* doneCallback();
* }
* }
* }
* ```
*
* \@experimental
*/
var NgZone = (function () {
/**
* @param {?} __0
*/
function NgZone(_a) {
var _b = _a.enableLongStackTrace, enableLongStackTrace = _b === void 0 ? false : _b;
this._hasPendingMicrotasks = false;
this._hasPendingMacrotasks = false;
this._isStable = true;
this._nesting = 0;
this._onUnstable = new EventEmitter(false);
this._onMicrotaskEmpty = new EventEmitter(false);
this._onStable = new EventEmitter(false);
this._onErrorEvents = new EventEmitter(false);
if (typeof Zone == 'undefined') {
throw new Error('Angular requires Zone.js prolyfill.');
}
Zone.assertZonePatched();
this.outer = this.inner = Zone.current;
if (Zone['wtfZoneSpec']) {
this.inner = this.inner.fork(Zone['wtfZoneSpec']);
}
if (enableLongStackTrace && Zone['longStackTraceZoneSpec']) {
this.inner = this.inner.fork(Zone['longStackTraceZoneSpec']);
}
this.forkInnerZoneWithAngularBehavior();
}
/**
* @return {?}
*/
NgZone.isInAngularZone = function () { return Zone.current.get('isAngularZone') === true; };
/**
* @return {?}
*/
NgZone.assertInAngularZone = function () {
if (!NgZone.isInAngularZone()) {
throw new Error('Expected to be in Angular Zone, but it is not!');
}
};
/**
* @return {?}
*/
NgZone.assertNotInAngularZone = function () {
if (NgZone.isInAngularZone()) {
throw new Error('Expected to not be in Angular Zone, but it is!');
}
};
/**
* Executes the `fn` function synchronously within the Angular zone and returns value returned by
* the function.
*
* Running functions via `run` allows you to reenter Angular zone from a task that was executed
* outside of the Angular zone (typically started via {\@link #runOutsideAngular}).
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* within the Angular zone.
*
* If a synchronous error happens it will be rethrown and not reported via `onError`.
* @param {?} fn
* @return {?}
*/
NgZone.prototype.run = function (fn) { return this.inner.run(fn); };
/**
* Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not
* rethrown.
* @param {?} fn
* @return {?}
*/
NgZone.prototype.runGuarded = function (fn) { return this.inner.runGuarded(fn); };
/**
* Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
* the function.
*
* Running functions via {\@link #runOutsideAngular} allows you to escape Angular's zone and do
* work that
* doesn't trigger Angular change-detection or is subject to Angular's error handling.
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* outside of the Angular zone.
*
* Use {\@link #run} to reenter the Angular zone and do work that updates the application model.
* @param {?} fn
* @return {?}
*/
NgZone.prototype.runOutsideAngular = function (fn) { return this.outer.run(fn); };
Object.defineProperty(NgZone.prototype, "onUnstable", {
/**
* Notifies when code enters Angular Zone. This gets fired first on VM Turn.
* @return {?}
*/
get: function () { return this._onUnstable; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgZone.prototype, "onMicrotaskEmpty", {
/**
* Notifies when there is no more microtasks enqueue in the current VM Turn.
* This is a hint for Angular to do change detection, which may enqueue more microtasks.
* For this reason this event can fire multiple times per VM Turn.
* @return {?}
*/
get: function () { return this._onMicrotaskEmpty; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgZone.prototype, "onStable", {
/**
* Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
* implies we are about to relinquish VM turn.
* This event gets called just once.
* @return {?}
*/
get: function () { return this._onStable; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgZone.prototype, "onError", {
/**
* Notify that an error has been delivered.
* @return {?}
*/
get: function () { return this._onErrorEvents; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgZone.prototype, "isStable", {
/**
* Whether there are no outstanding microtasks or macrotasks.
* @return {?}
*/
get: function () { return this._isStable; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgZone.prototype, "hasPendingMicrotasks", {
/**
* @return {?}
*/
get: function () { return this._hasPendingMicrotasks; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgZone.prototype, "hasPendingMacrotasks", {
/**
* @return {?}
*/
get: function () { return this._hasPendingMacrotasks; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
NgZone.prototype.checkStable = function () {
var _this = this;
if (this._nesting == 0 && !this._hasPendingMicrotasks && !this._isStable) {
try {
this._nesting++;
this._onMicrotaskEmpty.emit(null);
}
finally {
this._nesting--;
if (!this._hasPendingMicrotasks) {
try {
this.runOutsideAngular(function () { return _this._onStable.emit(null); });
}
finally {
this._isStable = true;
}
}
}
}
};
/**
* @return {?}
*/
NgZone.prototype.forkInnerZoneWithAngularBehavior = function () {
var _this = this;
this.inner = this.inner.fork({
name: 'angular',
properties: /** @type {?} */ ({ 'isAngularZone': true }),
onInvokeTask: function (delegate, current, target, task, applyThis, applyArgs) {
try {
_this.onEnter();
return delegate.invokeTask(target, task, applyThis, applyArgs);
}
finally {
_this.onLeave();
}
},
onInvoke: function (delegate, current, target, callback, applyThis, applyArgs, source) {
try {
_this.onEnter();
return delegate.invoke(target, callback, applyThis, applyArgs, source);
}
finally {
_this.onLeave();
}
},
onHasTask: function (delegate, current, target, hasTaskState) {
delegate.hasTask(target, hasTaskState);
if (current === target) {
// We are only interested in hasTask events which originate from our zone
// (A child hasTask event is not interesting to us)
if (hasTaskState.change == 'microTask') {
_this.setHasMicrotask(hasTaskState.microTask);
}
else if (hasTaskState.change == 'macroTask') {
_this.setHasMacrotask(hasTaskState.macroTask);
}
}
},
onHandleError: function (delegate, current, target, error) {
delegate.handleError(target, error);
_this.triggerError(error);
return false;
}
});
};
/**
* @return {?}
*/
NgZone.prototype.onEnter = function () {
this._nesting++;
if (this._isStable) {
this._isStable = false;
this._onUnstable.emit(null);
}
};
/**
* @return {?}
*/
NgZone.prototype.onLeave = function () {
this._nesting--;
this.checkStable();
};
/**
* @param {?} hasMicrotasks
* @return {?}
*/
NgZone.prototype.setHasMicrotask = function (hasMicrotasks) {
this._hasPendingMicrotasks = hasMicrotasks;
this.checkStable();
};
/**
* @param {?} hasMacrotasks
* @return {?}
*/
NgZone.prototype.setHasMacrotask = function (hasMacrotasks) { this._hasPendingMacrotasks = hasMacrotasks; };
/**
* @param {?} error
* @return {?}
*/
NgZone.prototype.triggerError = function (error) { this._onErrorEvents.emit(error); };
return NgZone;
}());
/**
* @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
*/
/**
* The Testability service provides testing hooks that can be accessed from
* the browser and by services such as Protractor. Each bootstrapped Angular
* application on the page will have an instance of Testability.
* \@experimental
*/
var Testability = (function () {
/**
* @param {?} _ngZone
*/
function Testability(_ngZone) {
this._ngZone = _ngZone;
/**
* \@internal
*/
this._pendingCount = 0;
/**
* \@internal
*/
this._isZoneStable = true;
/**
* Whether any work was done since the last 'whenStable' callback. This is
* useful to detect if this could have potentially destabilized another
* component while it is stabilizing.
* \@internal
*/
this._didWork = false;
/**
* \@internal
*/
this._callbacks = [];
this._watchAngularEvents();
}
/**
* \@internal
* @return {?}
*/
Testability.prototype._watchAngularEvents = function () {
var _this = this;
this._ngZone.onUnstable.subscribe({
next: function () {
_this._didWork = true;
_this._isZoneStable = false;
}
});
this._ngZone.runOutsideAngular(function () {
_this._ngZone.onStable.subscribe({
next: function () {
NgZone.assertNotInAngularZone();
scheduleMicroTask(function () {
_this._isZoneStable = true;
_this._runCallbacksIfReady();
});
}
});
});
};
/**
* @return {?}
*/
Testability.prototype.increasePendingRequestCount = function () {
this._pendingCount += 1;
this._didWork = true;
return this._pendingCount;
};
/**
* @return {?}
*/
Testability.prototype.decreasePendingRequestCount = function () {
this._pendingCount -= 1;
if (this._pendingCount < 0) {
throw new Error('pending async requests below zero');
}
this._runCallbacksIfReady();
return this._pendingCount;
};
/**
* @return {?}
*/
Testability.prototype.isStable = function () {
return this._isZoneStable && this._pendingCount == 0 && !this._ngZone.hasPendingMacrotasks;
};
/**
* \@internal
* @return {?}
*/
Testability.prototype._runCallbacksIfReady = function () {
var _this = this;
if (this.isStable()) {
// Schedules the call backs in a new frame so that it is always async.
scheduleMicroTask(function () {
while (_this._callbacks.length !== 0) {
(((_this._callbacks.pop())))(_this._didWork);
}
_this._didWork = false;
});
}
else {
// Not Ready
this._didWork = true;
}
};
/**
* @param {?} callback
* @return {?}
*/
Testability.prototype.whenStable = function (callback) {
this._callbacks.push(callback);
this._runCallbacksIfReady();
};
/**
* @return {?}
*/
Testability.prototype.getPendingRequestCount = function () { return this._pendingCount; };
/**
* @deprecated use findProviders
* @param {?} using
* @param {?} provider
* @param {?} exactMatch
* @return {?}
*/
Testability.prototype.findBindings = function (using, provider, exactMatch) {
// TODO(juliemr): implement.
return [];
};
/**
* @param {?} using
* @param {?} provider
* @param {?} exactMatch
* @return {?}
*/
Testability.prototype.findProviders = function (using, provider, exactMatch) {
// TODO(juliemr): implement.
return [];
};
return Testability;
}());
Testability.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
Testability.ctorParameters = function () { return [
{ type: NgZone, },
]; };
/**
* A global registry of {\@link Testability} instances for specific elements.
* \@experimental
*/
var TestabilityRegistry = (function () {
function TestabilityRegistry() {
/**
* \@internal
*/
this._applications = new Map();
_testabilityGetter.addToWindow(this);
}
/**
* @param {?} token
* @param {?} testability
* @return {?}
*/
TestabilityRegistry.prototype.registerApplication = function (token, testability) {
this._applications.set(token, testability);
};
/**
* @param {?} elem
* @return {?}
*/
TestabilityRegistry.prototype.getTestability = function (elem) { return this._applications.get(elem) || null; };
/**
* @return {?}
*/
TestabilityRegistry.prototype.getAllTestabilities = function () { return Array.from(this._applications.values()); };
/**
* @return {?}
*/
TestabilityRegistry.prototype.getAllRootElements = function () { return Array.from(this._applications.keys()); };
/**
* @param {?} elem
* @param {?=} findInAncestors
* @return {?}
*/
TestabilityRegistry.prototype.findTestabilityInTree = function (elem, findInAncestors) {
if (findInAncestors === void 0) { findInAncestors = true; }
return _testabilityGetter.findTestabilityInTree(this, elem, findInAncestors);
};
return TestabilityRegistry;
}());
TestabilityRegistry.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
TestabilityRegistry.ctorParameters = function () { return []; };
var _NoopGetTestability = (function () {
function _NoopGetTestability() {
}
/**
* @param {?} registry
* @return {?}
*/
_NoopGetTestability.prototype.addToWindow = function (registry) { };
/**
* @param {?} registry
* @param {?} elem
* @param {?} findInAncestors
* @return {?}
*/
_NoopGetTestability.prototype.findTestabilityInTree = function (registry, elem, findInAncestors) {
return null;
};
return _NoopGetTestability;
}());
/**
* Set the {\@link GetTestability} implementation used by the Angular testing framework.
* \@experimental
* @param {?} getter
* @return {?}
*/
function setTestabilityGetter(getter) {
_testabilityGetter = getter;
}
var _testabilityGetter = new _NoopGetTestability();
/**
* @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
*/
var _devMode = true;
var _runModeLocked = false;
var _platform;
var ALLOW_MULTIPLE_PLATFORMS = new InjectionToken('AllowMultipleToken');
/**
* Disable Angular's development mode, which turns off assertions and other
* checks within the framework.
*
* One important assertion this disables verifies that a change detection pass
* does not result in additional changes to any bindings (also known as
* unidirectional data flow).
*
* \@stable
* @return {?}
*/
function enableProdMode() {
if (_runModeLocked) {
throw new Error('Cannot enable prod mode after platform setup.');
}
_devMode = false;
}
/**
* Returns whether Angular is in development mode. After called once,
* the value is locked and won't change any more.
*
* By default, this is true, unless a user calls `enableProdMode` before calling this.
*
* \@experimental APIs related to application bootstrap are currently under review.
* @return {?}
*/
function isDevMode() {
_runModeLocked = true;
return _devMode;
}
/**
* A token for third-party components that can register themselves with NgProbe.
*
* \@experimental
*/
var NgProbeToken = (function () {
/**
* @param {?} name
* @param {?} token
*/
function NgProbeToken(name, token) {
this.name = name;
this.token = token;
}
return NgProbeToken;
}());
/**
* Creates a platform.
* Platforms have to be eagerly created via this function.
*
* \@experimental APIs related to application bootstrap are currently under review.
* @param {?} injector
* @return {?}
*/
function createPlatform(injector) {
if (_platform && !_platform.destroyed &&
!_platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
throw new Error('There can be only one platform. Destroy the previous one to create a new one.');
}
_platform = injector.get(PlatformRef);
var /** @type {?} */ inits = injector.get(PLATFORM_INITIALIZER, null);
if (inits)
inits.forEach(function (init) { return init(); });
return _platform;
}
/**
* Creates a factory for a platform
*
* \@experimental APIs related to application bootstrap are currently under review.
* @param {?} parentPlatformFactory
* @param {?} name
* @param {?=} providers
* @return {?}
*/
function createPlatformFactory(parentPlatformFactory, name, providers) {
if (providers === void 0) { providers = []; }
var /** @type {?} */ marker = new InjectionToken("Platform: " + name);
return function (extraProviders) {
if (extraProviders === void 0) { extraProviders = []; }
var /** @type {?} */ platform = getPlatform();
if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
if (parentPlatformFactory) {
parentPlatformFactory(providers.concat(extraProviders).concat({ provide: marker, useValue: true }));
}
else {
createPlatform(ReflectiveInjector.resolveAndCreate(providers.concat(extraProviders).concat({ provide: marker, useValue: true })));
}
}
return assertPlatform(marker);
};
}
/**
* Checks that there currently is a platform which contains the given token as a provider.
*
* \@experimental APIs related to application bootstrap are currently under review.
* @param {?} requiredToken
* @return {?}
*/
function assertPlatform(requiredToken) {
var /** @type {?} */ platform = getPlatform();
if (!platform) {
throw new Error('No platform exists!');
}
if (!platform.injector.get(requiredToken, null)) {
throw new Error('A platform with a different configuration has been created. Please destroy it first.');
}
return platform;
}
/**
* Destroy the existing platform.
*
* \@experimental APIs related to application bootstrap are currently under review.
* @return {?}
*/
function destroyPlatform() {
if (_platform && !_platform.destroyed) {
_platform.destroy();
}
}
/**
* Returns the current platform.
*
* \@experimental APIs related to application bootstrap are currently under review.
* @return {?}
*/
function getPlatform() {
return _platform && !_platform.destroyed ? _platform : null;
}
/**
* The Angular platform is the entry point for Angular on a web page. Each page
* has exactly one platform, and services (such as reflection) which are common
* to every Angular application running on the page are bound in its scope.
*
* A page's platform is initialized implicitly when a platform is created via a platform factory
* (e.g. {\@link platformBrowser}), or explicitly by calling the {\@link createPlatform} function.
*
* \@stable
* @abstract
*/
var PlatformRef = (function () {
function PlatformRef() {
}
/**
* Creates an instance of an `\@NgModule` for the given platform
* for offline compilation.
*
* ## Simple Example
*
* ```typescript
* my_module.ts:
*
* \@NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* main.ts:
* import {MyModuleNgFactory} from './my_module.ngfactory';
* import {platformBrowser} from '\@angular/platform-browser';
*
* let moduleRef = platformBrowser().bootstrapModuleFactory(MyModuleNgFactory);
* ```
*
* \@experimental APIs related to application bootstrap are currently under review.
* @abstract
* @template M
* @param {?} moduleFactory
* @return {?}
*/
PlatformRef.prototype.bootstrapModuleFactory = function (moduleFactory) { };
/**
* Creates an instance of an `\@NgModule` for a given platform using the given runtime compiler.
*
* ## Simple Example
*
* ```typescript
* \@NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* let moduleRef = platformBrowser().bootstrapModule(MyModule);
* ```
* \@stable
* @abstract
* @template M
* @param {?} moduleType
* @param {?=} compilerOptions
* @return {?}
*/
PlatformRef.prototype.bootstrapModule = function (moduleType, compilerOptions) { };
/**
* Register a listener to be called when the platform is disposed.
* @abstract
* @param {?} callback
* @return {?}
*/
PlatformRef.prototype.onDestroy = function (callback) { };
/**
* Retrieve the platform {\@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton providers.
* @abstract
* @return {?}
*/
PlatformRef.prototype.injector = function () { };
/**
* Destroy the Angular platform and all Angular applications on the page.
* @abstract
* @return {?}
*/
PlatformRef.prototype.destroy = function () { };
/**
* @abstract
* @return {?}
*/
PlatformRef.prototype.destroyed = function () { };
return PlatformRef;
}());
/**
* @param {?} errorHandler
* @param {?} callback
* @return {?}
*/
function _callAndReportToErrorHandler(errorHandler, callback) {
try {
var /** @type {?} */ result = callback();
if (isPromise(result)) {
return result.catch(function (e) {
errorHandler.handleError(e);
// rethrow as the exception handler might not do it
throw e;
});
}
return result;
}
catch (e) {
errorHandler.handleError(e);
// rethrow as the exception handler might not do it
throw e;
}
}
/**
* workaround https://github.com/angular/tsickle/issues/350
* @suppress {checkTypes}
*/
var PlatformRef_ = (function (_super) {
__extends(PlatformRef_, _super);
/**
* @param {?} _injector
*/
function PlatformRef_(_injector) {
var _this = _super.call(this) || this;
_this._injector = _injector;
_this._modules = [];
_this._destroyListeners = [];
_this._destroyed = false;
return _this;
}
/**
* @param {?} callback
* @return {?}
*/
PlatformRef_.prototype.onDestroy = function (callback) { this._destroyListeners.push(callback); };
Object.defineProperty(PlatformRef_.prototype, "injector", {
/**
* @return {?}
*/
get: function () { return this._injector; },
enumerable: true,
configurable: true
});
Object.defineProperty(PlatformRef_.prototype, "destroyed", {
/**
* @return {?}
*/
get: function () { return this._destroyed; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
PlatformRef_.prototype.destroy = function () {
if (this._destroyed) {
throw new Error('The platform has already been destroyed!');
}
this._modules.slice().forEach(function (module) { return module.destroy(); });
this._destroyListeners.forEach(function (listener) { return listener(); });
this._destroyed = true;
};
/**
* @template M
* @param {?} moduleFactory
* @return {?}
*/
PlatformRef_.prototype.bootstrapModuleFactory = function (moduleFactory) {
return this._bootstrapModuleFactoryWithZone(moduleFactory);
};
/**
* @template M
* @param {?} moduleFactory
* @param {?=} ngZone
* @return {?}
*/
PlatformRef_.prototype._bootstrapModuleFactoryWithZone = function (moduleFactory, ngZone) {
var _this = this;
// Note: We need to create the NgZone _before_ we instantiate the module,
// as instantiating the module creates some providers eagerly.
// So we create a mini parent injector that just contains the new NgZone and
// pass that as parent to the NgModuleFactory.
if (!ngZone)
ngZone = new NgZone({ enableLongStackTrace: isDevMode() });
// Attention: Don't use ApplicationRef.run here,
// as we want to be sure that all possible constructor calls are inside `ngZone.run`!
return ngZone.run(function () {
var /** @type {?} */ ngZoneInjector = ReflectiveInjector.resolveAndCreate([{ provide: NgZone, useValue: ngZone }], _this.injector);
var /** @type {?} */ moduleRef = (moduleFactory.create(ngZoneInjector));
var /** @type {?} */ exceptionHandler = moduleRef.injector.get(ErrorHandler, null);
if (!exceptionHandler) {
throw new Error('No ErrorHandler. Is platform module (BrowserModule) included?');
}
moduleRef.onDestroy(function () { return remove(_this._modules, moduleRef); }); /** @type {?} */
((ngZone)).onError.subscribe({ next: function (error) { exceptionHandler.handleError(error); } });
return _callAndReportToErrorHandler(exceptionHandler, function () {
var /** @type {?} */ initStatus = moduleRef.injector.get(ApplicationInitStatus);
return initStatus.donePromise.then(function () {
_this._moduleDoBootstrap(moduleRef);
return moduleRef;
});
});
});
};
/**
* @template M
* @param {?} moduleType
* @param {?=} compilerOptions
* @return {?}
*/
PlatformRef_.prototype.bootstrapModule = function (moduleType, compilerOptions) {
if (compilerOptions === void 0) { compilerOptions = []; }
return this._bootstrapModuleWithZone(moduleType, compilerOptions);
};
/**
* @template M
* @param {?} moduleType
* @param {?=} compilerOptions
* @param {?=} ngZone
* @return {?}
*/
PlatformRef_.prototype._bootstrapModuleWithZone = function (moduleType, compilerOptions, ngZone) {
var _this = this;
if (compilerOptions === void 0) { compilerOptions = []; }
var /** @type {?} */ compilerFactory = this.injector.get(CompilerFactory);
var /** @type {?} */ compiler = compilerFactory.createCompiler(Array.isArray(compilerOptions) ? compilerOptions : [compilerOptions]);
return compiler.compileModuleAsync(moduleType)
.then(function (moduleFactory) { return _this._bootstrapModuleFactoryWithZone(moduleFactory, ngZone); });
};
/**
* @param {?} moduleRef
* @return {?}
*/
PlatformRef_.prototype._moduleDoBootstrap = function (moduleRef) {
var /** @type {?} */ appRef = moduleRef.injector.get(ApplicationRef);
if (moduleRef.bootstrapFactories.length > 0) {
moduleRef.bootstrapFactories.forEach(function (f) { return appRef.bootstrap(f); });
}
else if (moduleRef.instance.ngDoBootstrap) {
moduleRef.instance.ngDoBootstrap(appRef);
}
else {
throw new Error("The module " + stringify(moduleRef.instance.constructor) + " was bootstrapped, but it does not declare \"@NgModule.bootstrap\" components nor a \"ngDoBootstrap\" method. " +
"Please define one of these.");
}
this._modules.push(moduleRef);
};
return PlatformRef_;
}(PlatformRef));
PlatformRef_.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
PlatformRef_.ctorParameters = function () { return [
{ type: Injector, },
]; };
/**
* A reference to an Angular application running on a page.
*
* \@stable
* @abstract
*/
var ApplicationRef = (function () {
function ApplicationRef() {
}
/**
* Bootstrap a new component at the root level of the application.
*
* ### Bootstrap process
*
* When bootstrapping a new root component into an application, Angular mounts the
* specified application component onto DOM elements identified by the [componentType]'s
* selector and kicks off automatic change detection to finish initializing the component.
*
* ### Example
* {\@example core/ts/platform/platform.ts region='longform'}
* @abstract
* @template C
* @param {?} componentFactory
* @return {?}
*/
ApplicationRef.prototype.bootstrap = function (componentFactory) { };
/**
* Invoke this method to explicitly process change detection and its side-effects.
*
* In development mode, `tick()` also performs a second change detection cycle to ensure that no
* further changes are detected. If additional changes are picked up during this second cycle,
* bindings in the app have side-effects that cannot be resolved in a single change detection
* pass.
* In this case, Angular throws an error, since an Angular application can only have one change
* detection pass during which all change detection must complete.
* @abstract
* @return {?}
*/
ApplicationRef.prototype.tick = function () { };
/**
* Get a list of component types registered to this application.
* This list is populated even before the component is created.
* @abstract
* @return {?}
*/
ApplicationRef.prototype.componentTypes = function () { };
/**
* Get a list of components registered to this application.
* @abstract
* @return {?}
*/
ApplicationRef.prototype.components = function () { };
/**
* Attaches a view so that it will be dirty checked.
* The view will be automatically detached when it is destroyed.
* This will throw if the view is already attached to a ViewContainer.
* @abstract
* @param {?} view
* @return {?}
*/
ApplicationRef.prototype.attachView = function (view) { };
/**
* Detaches a view from dirty checking again.
* @abstract
* @param {?} view
* @return {?}
*/
ApplicationRef.prototype.detachView = function (view) { };
/**
* Returns the number of attached views.
* @abstract
* @return {?}
*/
ApplicationRef.prototype.viewCount = function () { };
/**
* Returns an Observable that indicates when the application is stable or unstable.
* @abstract
* @return {?}
*/
ApplicationRef.prototype.isStable = function () { };
return ApplicationRef;
}());
/**
* workaround https://github.com/angular/tsickle/issues/350
* @suppress {checkTypes}
*/
var ApplicationRef_ = (function (_super) {
__extends(ApplicationRef_, _super);
/**
* @param {?} _zone
* @param {?} _console
* @param {?} _injector
* @param {?} _exceptionHandler
* @param {?} _componentFactoryResolver
* @param {?} _initStatus
*/
function ApplicationRef_(_zone, _console, _injector, _exceptionHandler, _componentFactoryResolver, _initStatus) {
var _this = _super.call(this) || this;
_this._zone = _zone;
_this._console = _console;
_this._injector = _injector;
_this._exceptionHandler = _exceptionHandler;
_this._componentFactoryResolver = _componentFactoryResolver;
_this._initStatus = _initStatus;
_this._bootstrapListeners = [];
_this._rootComponents = [];
_this._rootComponentTypes = [];
_this._views = [];
_this._runningTick = false;
_this._enforceNoNewChanges = false;
_this._stable = true;
_this._enforceNoNewChanges = isDevMode();
_this._zone.onMicrotaskEmpty.subscribe({ next: function () { _this._zone.run(function () { _this.tick(); }); } });
var isCurrentlyStable = new __WEBPACK_IMPORTED_MODULE_0_rxjs_Observable__["Observable"](function (observer) {
_this._stable = _this._zone.isStable && !_this._zone.hasPendingMacrotasks &&
!_this._zone.hasPendingMicrotasks;
_this._zone.runOutsideAngular(function () {
observer.next(_this._stable);
observer.complete();
});
});
var isStable = new __WEBPACK_IMPORTED_MODULE_0_rxjs_Observable__["Observable"](function (observer) {
var stableSub = _this._zone.onStable.subscribe(function () {
NgZone.assertNotInAngularZone();
// Check whether there are no pending macro/micro tasks in the next tick
// to allow for NgZone to update the state.
scheduleMicroTask(function () {
if (!_this._stable && !_this._zone.hasPendingMacrotasks &&
!_this._zone.hasPendingMicrotasks) {
_this._stable = true;
observer.next(true);
}
});
});
var unstableSub = _this._zone.onUnstable.subscribe(function () {
NgZone.assertInAngularZone();
if (_this._stable) {
_this._stable = false;
_this._zone.runOutsideAngular(function () { observer.next(false); });
}
});
return function () {
stableSub.unsubscribe();
unstableSub.unsubscribe();
};
});
_this._isStable = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_rxjs_observable_merge__["merge"])(isCurrentlyStable, __WEBPACK_IMPORTED_MODULE_2_rxjs_operator_share__["share"].call(isStable));
return _this;
}
/**
* @param {?} viewRef
* @return {?}
*/
ApplicationRef_.prototype.attachView = function (viewRef) {
var /** @type {?} */ view = ((viewRef));
this._views.push(view);
view.attachToAppRef(this);
};
/**
* @param {?} viewRef
* @return {?}
*/
ApplicationRef_.prototype.detachView = function (viewRef) {
var /** @type {?} */ view = ((viewRef));
remove(this._views, view);
view.detachFromAppRef();
};
/**
* @template C
* @param {?} componentOrFactory
* @return {?}
*/
ApplicationRef_.prototype.bootstrap = function (componentOrFactory) {
var _this = this;
if (!this._initStatus.done) {
throw new Error('Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.');
}
var /** @type {?} */ componentFactory;
if (componentOrFactory instanceof ComponentFactory) {
componentFactory = componentOrFactory;
}
else {
componentFactory = ((this._componentFactoryResolver.resolveComponentFactory(componentOrFactory)));
}
this._rootComponentTypes.push(componentFactory.componentType);
// Create a factory associated with the current module if it's not bound to some other
var /** @type {?} */ ngModule = componentFactory instanceof ComponentFactoryBoundToModule ?
null :
this._injector.get(NgModuleRef);
var /** @type {?} */ compRef = componentFactory.create(Injector.NULL, [], componentFactory.selector, ngModule);
compRef.onDestroy(function () { _this._unloadComponent(compRef); });
var /** @type {?} */ testability = compRef.injector.get(Testability, null);
if (testability) {
compRef.injector.get(TestabilityRegistry)
.registerApplication(compRef.location.nativeElement, testability);
}
this._loadComponent(compRef);
if (isDevMode()) {
this._console.log("Angular is running in the development mode. Call enableProdMode() to enable the production mode.");
}
return compRef;
};
/**
* @param {?} componentRef
* @return {?}
*/
ApplicationRef_.prototype._loadComponent = function (componentRef) {
this.attachView(componentRef.hostView);
this.tick();
this._rootComponents.push(componentRef);
// Get the listeners lazily to prevent DI cycles.
var /** @type {?} */ listeners = this._injector.get(APP_BOOTSTRAP_LISTENER, []).concat(this._bootstrapListeners);
listeners.forEach(function (listener) { return listener(componentRef); });
};
/**
* @param {?} componentRef
* @return {?}
*/
ApplicationRef_.prototype._unloadComponent = function (componentRef) {
this.detachView(componentRef.hostView);
remove(this._rootComponents, componentRef);
};
/**
* @return {?}
*/
ApplicationRef_.prototype.tick = function () {
if (this._runningTick) {
throw new Error('ApplicationRef.tick is called recursively');
}
var /** @type {?} */ scope = ApplicationRef_._tickScope();
try {
this._runningTick = true;
this._views.forEach(function (view) { return view.detectChanges(); });
if (this._enforceNoNewChanges) {
this._views.forEach(function (view) { return view.checkNoChanges(); });
}
}
catch (e) {
// Attention: Don't rethrow as it could cancel subscriptions to Observables!
this._exceptionHandler.handleError(e);
}
finally {
this._runningTick = false;
wtfLeave(scope);
}
};
/**
* @return {?}
*/
ApplicationRef_.prototype.ngOnDestroy = function () {
// TODO(alxhub): Dispose of the NgZone.
this._views.slice().forEach(function (view) { return view.destroy(); });
};
Object.defineProperty(ApplicationRef_.prototype, "viewCount", {
/**
* @return {?}
*/
get: function () { return this._views.length; },
enumerable: true,
configurable: true
});
Object.defineProperty(ApplicationRef_.prototype, "componentTypes", {
/**
* @return {?}
*/
get: function () { return this._rootComponentTypes; },
enumerable: true,
configurable: true
});
Object.defineProperty(ApplicationRef_.prototype, "components", {
/**
* @return {?}
*/
get: function () { return this._rootComponents; },
enumerable: true,
configurable: true
});
Object.defineProperty(ApplicationRef_.prototype, "isStable", {
/**
* @return {?}
*/
get: function () { return this._isStable; },
enumerable: true,
configurable: true
});
return ApplicationRef_;
}(ApplicationRef));
/**
* \@internal
*/
ApplicationRef_._tickScope = wtfCreateScope('ApplicationRef#tick()');
ApplicationRef_.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
ApplicationRef_.ctorParameters = function () { return [
{ type: NgZone, },
{ type: Console, },
{ type: Injector, },
{ type: ErrorHandler, },
{ type: ComponentFactoryResolver, },
{ type: ApplicationInitStatus, },
]; };
/**
* @template T
* @param {?} list
* @param {?} el
* @return {?}
*/
function remove(list, el) {
var /** @type {?} */ index = list.indexOf(el);
if (index > -1) {
list.splice(index, 1);
}
}
/**
* @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
*/
// Public API for Zone
/**
* @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
*/
/**
* @deprecated Use `RendererType2` (and `Renderer2`) instead.
*/
var RenderComponentType = (function () {
/**
* @param {?} id
* @param {?} templateUrl
* @param {?} slotCount
* @param {?} encapsulation
* @param {?} styles
* @param {?} animations
*/
function RenderComponentType(id, templateUrl, slotCount, encapsulation, styles, animations) {
this.id = id;
this.templateUrl = templateUrl;
this.slotCount = slotCount;
this.encapsulation = encapsulation;
this.styles = styles;
this.animations = animations;
}
return RenderComponentType;
}());
/**
* @deprecated Debug info is handeled internally in the view engine now.
* @abstract
*/
var RenderDebugInfo = (function () {
function RenderDebugInfo() {
}
/**
* @abstract
* @return {?}
*/
RenderDebugInfo.prototype.injector = function () { };
/**
* @abstract
* @return {?}
*/
RenderDebugInfo.prototype.component = function () { };
/**
* @abstract
* @return {?}
*/
RenderDebugInfo.prototype.providerTokens = function () { };
/**
* @abstract
* @return {?}
*/
RenderDebugInfo.prototype.references = function () { };
/**
* @abstract
* @return {?}
*/
RenderDebugInfo.prototype.context = function () { };
/**
* @abstract
* @return {?}
*/
RenderDebugInfo.prototype.source = function () { };
return RenderDebugInfo;
}());
/**
* @deprecated Use the `Renderer2` instead.
* @abstract
*/
var Renderer = (function () {
function Renderer() {
}
/**
* @abstract
* @param {?} selectorOrNode
* @param {?=} debugInfo
* @return {?}
*/
Renderer.prototype.selectRootElement = function (selectorOrNode, debugInfo) { };
/**
* @abstract
* @param {?} parentElement
* @param {?} name
* @param {?=} debugInfo
* @return {?}
*/
Renderer.prototype.createElement = function (parentElement, name, debugInfo) { };
/**
* @abstract
* @param {?} hostElement
* @return {?}
*/
Renderer.prototype.createViewRoot = function (hostElement) { };
/**
* @abstract
* @param {?} parentElement
* @param {?=} debugInfo
* @return {?}
*/
Renderer.prototype.createTemplateAnchor = function (parentElement, debugInfo) { };
/**
* @abstract
* @param {?} parentElement
* @param {?} value
* @param {?=} debugInfo
* @return {?}
*/
Renderer.prototype.createText = function (parentElement, value, debugInfo) { };
/**
* @abstract
* @param {?} parentElement
* @param {?} nodes
* @return {?}
*/
Renderer.prototype.projectNodes = function (parentElement, nodes) { };
/**
* @abstract
* @param {?} node
* @param {?} viewRootNodes
* @return {?}
*/
Renderer.prototype.attachViewAfter = function (node, viewRootNodes) { };
/**
* @abstract
* @param {?} viewRootNodes
* @return {?}
*/
Renderer.prototype.detachView = function (viewRootNodes) { };
/**
* @abstract
* @param {?} hostElement
* @param {?} viewAllNodes
* @return {?}
*/
Renderer.prototype.destroyView = function (hostElement, viewAllNodes) { };
/**
* @abstract
* @param {?} renderElement
* @param {?} name
* @param {?} callback
* @return {?}
*/
Renderer.prototype.listen = function (renderElement, name, callback) { };
/**
* @abstract
* @param {?} target
* @param {?} name
* @param {?} callback
* @return {?}
*/
Renderer.prototype.listenGlobal = function (target, name, callback) { };
/**
* @abstract
* @param {?} renderElement
* @param {?} propertyName
* @param {?} propertyValue
* @return {?}
*/
Renderer.prototype.setElementProperty = function (renderElement, propertyName, propertyValue) { };
/**
* @abstract
* @param {?} renderElement
* @param {?} attributeName
* @param {?} attributeValue
* @return {?}
*/
Renderer.prototype.setElementAttribute = function (renderElement, attributeName, attributeValue) { };
/**
* Used only in debug mode to serialize property changes to dom nodes as attributes.
* @abstract
* @param {?} renderElement
* @param {?} propertyName
* @param {?} propertyValue
* @return {?}
*/
Renderer.prototype.setBindingDebugInfo = function (renderElement, propertyName, propertyValue) { };
/**
* @abstract
* @param {?} renderElement
* @param {?} className
* @param {?} isAdd
* @return {?}
*/
Renderer.prototype.setElementClass = function (renderElement, className, isAdd) { };
/**
* @abstract
* @param {?} renderElement
* @param {?} styleName
* @param {?} styleValue
* @return {?}
*/
Renderer.prototype.setElementStyle = function (renderElement, styleName, styleValue) { };
/**
* @abstract
* @param {?} renderElement
* @param {?} methodName
* @param {?=} args
* @return {?}
*/
Renderer.prototype.invokeElementMethod = function (renderElement, methodName, args) { };
/**
* @abstract
* @param {?} renderNode
* @param {?} text
* @return {?}
*/
Renderer.prototype.setText = function (renderNode, text) { };
/**
* @abstract
* @param {?} element
* @param {?} startingStyles
* @param {?} keyframes
* @param {?} duration
* @param {?} delay
* @param {?} easing
* @param {?=} previousPlayers
* @return {?}
*/
Renderer.prototype.animate = function (element, startingStyles, keyframes, duration, delay, easing, previousPlayers) { };
return Renderer;
}());
var Renderer2Interceptor = new InjectionToken('Renderer2Interceptor');
/**
* Injectable service that provides a low-level interface for modifying the UI.
*
* Use this service to bypass Angular's templating and make custom UI changes that can't be
* expressed declaratively. For example if you need to set a property or an attribute whose name is
* not statically known, use {\@link #setElementProperty} or {\@link #setElementAttribute}
* respectively.
*
* If you are implementing a custom renderer, you must implement this interface.
*
* The default Renderer implementation is `DomRenderer`. Also available is `WebWorkerRenderer`.
*
* @deprecated Use `RendererFactory2` instead.
* @abstract
*/
var RootRenderer = (function () {
function RootRenderer() {
}
/**
* @abstract
* @param {?} componentType
* @return {?}
*/
RootRenderer.prototype.renderComponent = function (componentType) { };
return RootRenderer;
}());
/**
* \@experimental
* @abstract
*/
var RendererFactory2 = (function () {
function RendererFactory2() {
}
/**
* @abstract
* @param {?} hostElement
* @param {?} type
* @return {?}
*/
RendererFactory2.prototype.createRenderer = function (hostElement, type) { };
return RendererFactory2;
}());
var RendererStyleFlags2 = {};
RendererStyleFlags2.Important = 1;
RendererStyleFlags2.DashCase = 2;
RendererStyleFlags2[RendererStyleFlags2.Important] = "Important";
RendererStyleFlags2[RendererStyleFlags2.DashCase] = "DashCase";
/**
* \@experimental
* @abstract
*/
var Renderer2 = (function () {
function Renderer2() {
}
/**
* This field can be used to store arbitrary data on this renderer instance.
* This is useful for renderers that delegate to other renderers.
* @abstract
* @return {?}
*/
Renderer2.prototype.data = function () { };
/**
* @abstract
* @return {?}
*/
Renderer2.prototype.destroy = function () { };
/**
* @abstract
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
Renderer2.prototype.createElement = function (name, namespace) { };
/**
* @abstract
* @param {?} value
* @return {?}
*/
Renderer2.prototype.createComment = function (value) { };
/**
* @abstract
* @param {?} value
* @return {?}
*/
Renderer2.prototype.createText = function (value) { };
/**
* @abstract
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
Renderer2.prototype.appendChild = function (parent, newChild) { };
/**
* @abstract
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
Renderer2.prototype.insertBefore = function (parent, newChild, refChild) { };
/**
* @abstract
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
Renderer2.prototype.removeChild = function (parent, oldChild) { };
/**
* @abstract
* @param {?} selectorOrNode
* @return {?}
*/
Renderer2.prototype.selectRootElement = function (selectorOrNode) { };
/**
* Attention: On WebWorkers, this will always return a value,
* as we are asking for a result synchronously. I.e.
* the caller can't rely on checking whether this is null or not.
* @abstract
* @param {?} node
* @return {?}
*/
Renderer2.prototype.parentNode = function (node) { };
/**
* Attention: On WebWorkers, this will always return a value,
* as we are asking for a result synchronously. I.e.
* the caller can't rely on checking whether this is null or not.
* @abstract
* @param {?} node
* @return {?}
*/
Renderer2.prototype.nextSibling = function (node) { };
/**
* @abstract
* @param {?} el
* @param {?} name
* @param {?} value
* @param {?=} namespace
* @return {?}
*/
Renderer2.prototype.setAttribute = function (el, name, value, namespace) { };
/**
* @abstract
* @param {?} el
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
Renderer2.prototype.removeAttribute = function (el, name, namespace) { };
/**
* @abstract
* @param {?} el
* @param {?} name
* @return {?}
*/
Renderer2.prototype.addClass = function (el, name) { };
/**
* @abstract
* @param {?} el
* @param {?} name
* @return {?}
*/
Renderer2.prototype.removeClass = function (el, name) { };
/**
* @abstract
* @param {?} el
* @param {?} style
* @param {?} value
* @param {?=} flags
* @return {?}
*/
Renderer2.prototype.setStyle = function (el, style, value, flags) { };
/**
* @abstract
* @param {?} el
* @param {?} style
* @param {?=} flags
* @return {?}
*/
Renderer2.prototype.removeStyle = function (el, style, flags) { };
/**
* @abstract
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
Renderer2.prototype.setProperty = function (el, name, value) { };
/**
* @abstract
* @param {?} node
* @param {?} value
* @return {?}
*/
Renderer2.prototype.setValue = function (node, value) { };
/**
* @abstract
* @param {?} target
* @param {?} eventName
* @param {?} callback
* @return {?}
*/
Renderer2.prototype.listen = function (target, eventName, callback) { };
return Renderer2;
}());
/**
* @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
*/
// Public API for render
var ElementRef = (function () {
/**
* @param {?} nativeElement
*/
function ElementRef(nativeElement) {
this.nativeElement = nativeElement;
}
return ElementRef;
}());
/**
* @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
*/
/**
* Used to load ng module factories.
* \@stable
* @abstract
*/
var NgModuleFactoryLoader = (function () {
function NgModuleFactoryLoader() {
}
/**
* @abstract
* @param {?} path
* @return {?}
*/
NgModuleFactoryLoader.prototype.load = function (path) { };
return NgModuleFactoryLoader;
}());
var moduleFactories = new Map();
/**
* Registers a loaded module. Should only be called from generated NgModuleFactory code.
* \@experimental
* @param {?} id
* @param {?} factory
* @return {?}
*/
function registerModuleFactory(id, factory) {
var /** @type {?} */ existing = moduleFactories.get(id);
if (existing) {
throw new Error("Duplicate module registered for " + id + " - " + existing.moduleType.name + " vs " + factory.moduleType.name);
}
moduleFactories.set(id, factory);
}
/**
* @return {?}
*/
/**
* Returns the NgModuleFactory with the given id, if it exists and has been loaded.
* Factories for modules that do not specify an `id` cannot be retrieved. Throws if the module
* cannot be found.
* \@experimental
* @param {?} id
* @return {?}
*/
function getModuleFactory(id) {
var /** @type {?} */ factory = moduleFactories.get(id);
if (!factory)
throw new Error("No module with ID " + id + " loaded");
return factory;
}
/**
* @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
*/
/**
* An unmodifiable list of items that Angular keeps up to date when the state
* of the application changes.
*
* The type of object that {\@link ViewChildren}, {\@link ContentChildren}, and {\@link QueryList}
* provide.
*
* Implements an iterable interface, therefore it can be used in both ES6
* javascript `for (var i of items)` loops as well as in Angular templates with
* `*ngFor="let i of myList"`.
*
* Changes can be observed by subscribing to the changes `Observable`.
*
* NOTE: In the future this class will implement an `Observable` interface.
*
* ### Example ([live demo](http://plnkr.co/edit/RX8sJnQYl9FWuSCWme5z?p=preview))
* ```typescript
* \@Component({...})
* class Container {
* \@ViewChildren(Item) items:QueryList<Item>;
* }
* ```
* \@stable
*/
var QueryList = (function () {
function QueryList() {
this._dirty = true;
this._results = [];
this._emitter = new EventEmitter();
}
Object.defineProperty(QueryList.prototype, "changes", {
/**
* @return {?}
*/
get: function () { return this._emitter; },
enumerable: true,
configurable: true
});
Object.defineProperty(QueryList.prototype, "length", {
/**
* @return {?}
*/
get: function () { return this._results.length; },
enumerable: true,
configurable: true
});
Object.defineProperty(QueryList.prototype, "first", {
/**
* @return {?}
*/
get: function () { return this._results[0]; },
enumerable: true,
configurable: true
});
Object.defineProperty(QueryList.prototype, "last", {
/**
* @return {?}
*/
get: function () { return this._results[this.length - 1]; },
enumerable: true,
configurable: true
});
/**
* See
* [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
* @template U
* @param {?} fn
* @return {?}
*/
QueryList.prototype.map = function (fn) { return this._results.map(fn); };
/**
* See
* [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
* @param {?} fn
* @return {?}
*/
QueryList.prototype.filter = function (fn) {
return this._results.filter(fn);
};
/**
* See
* [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
* @param {?} fn
* @return {?}
*/
QueryList.prototype.find = function (fn) {
return this._results.find(fn);
};
/**
* See
* [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
* @template U
* @param {?} fn
* @param {?} init
* @return {?}
*/
QueryList.prototype.reduce = function (fn, init) {
return this._results.reduce(fn, init);
};
/**
* See
* [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
* @param {?} fn
* @return {?}
*/
QueryList.prototype.forEach = function (fn) { this._results.forEach(fn); };
/**
* See
* [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
* @param {?} fn
* @return {?}
*/
QueryList.prototype.some = function (fn) {
return this._results.some(fn);
};
/**
* @return {?}
*/
QueryList.prototype.toArray = function () { return this._results.slice(); };
/**
* @return {?}
*/
QueryList.prototype[getSymbolIterator()] = function () { return ((this._results))[getSymbolIterator()](); };
/**
* @return {?}
*/
QueryList.prototype.toString = function () { return this._results.toString(); };
/**
* @param {?} res
* @return {?}
*/
QueryList.prototype.reset = function (res) {
this._results = flatten(res);
this._dirty = false;
};
/**
* @return {?}
*/
QueryList.prototype.notifyOnChanges = function () { this._emitter.emit(this); };
/**
* internal
* @return {?}
*/
QueryList.prototype.setDirty = function () { this._dirty = true; };
Object.defineProperty(QueryList.prototype, "dirty", {
/**
* internal
* @return {?}
*/
get: function () { return this._dirty; },
enumerable: true,
configurable: true
});
return QueryList;
}());
/**
* @template T
* @param {?} list
* @return {?}
*/
function flatten(list) {
return list.reduce(function (flat, item) {
var /** @type {?} */ flatItem = Array.isArray(item) ? flatten(item) : item;
return ((flat)).concat(flatItem);
}, []);
}
/**
* @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
*/
var _SEPARATOR = '#';
var FACTORY_CLASS_SUFFIX = 'NgFactory';
/**
* Configuration for SystemJsNgModuleLoader.
* token.
*
* \@experimental
* @abstract
*/
var SystemJsNgModuleLoaderConfig = (function () {
function SystemJsNgModuleLoaderConfig() {
}
return SystemJsNgModuleLoaderConfig;
}());
var DEFAULT_CONFIG = {
factoryPathPrefix: '',
factoryPathSuffix: '.ngfactory',
};
/**
* NgModuleFactoryLoader that uses SystemJS to load NgModuleFactory
* \@experimental
*/
var SystemJsNgModuleLoader = (function () {
/**
* @param {?} _compiler
* @param {?=} config
*/
function SystemJsNgModuleLoader(_compiler, config) {
this._compiler = _compiler;
this._config = config || DEFAULT_CONFIG;
}
/**
* @param {?} path
* @return {?}
*/
SystemJsNgModuleLoader.prototype.load = function (path) {
var /** @type {?} */ offlineMode = this._compiler instanceof Compiler;
return offlineMode ? this.loadFactory(path) : this.loadAndCompile(path);
};
/**
* @param {?} path
* @return {?}
*/
SystemJsNgModuleLoader.prototype.loadAndCompile = function (path) {
var _this = this;
var _a = path.split(_SEPARATOR), module = _a[0], exportName = _a[1];
if (exportName === undefined) {
exportName = 'default';
}
return __webpack_require__(120)(module)
.then(function (module) { return module[exportName]; })
.then(function (type) { return checkNotEmpty(type, module, exportName); })
.then(function (type) { return _this._compiler.compileModuleAsync(type); });
};
/**
* @param {?} path
* @return {?}
*/
SystemJsNgModuleLoader.prototype.loadFactory = function (path) {
var _a = path.split(_SEPARATOR), module = _a[0], exportName = _a[1];
var /** @type {?} */ factoryClassSuffix = FACTORY_CLASS_SUFFIX;
if (exportName === undefined) {
exportName = 'default';
factoryClassSuffix = '';
}
return __webpack_require__(120)(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)
.then(function (module) { return module[exportName + factoryClassSuffix]; })
.then(function (factory) { return checkNotEmpty(factory, module, exportName); });
};
return SystemJsNgModuleLoader;
}());
SystemJsNgModuleLoader.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
SystemJsNgModuleLoader.ctorParameters = function () { return [
{ type: Compiler, },
{ type: SystemJsNgModuleLoaderConfig, decorators: [{ type: Optional },] },
]; };
/**
* @param {?} value
* @param {?} modulePath
* @param {?} exportName
* @return {?}
*/
function checkNotEmpty(value, modulePath, exportName) {
if (!value) {
throw new Error("Cannot find '" + exportName + "' in '" + modulePath + "'");
}
return value;
}
/**
* @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
*/
/**
* Represents an Embedded Template that can be used to instantiate Embedded Views.
*
* You can access a `TemplateRef`, in two ways. Via a directive placed on a `<ng-template>` element
* (or directive prefixed with `*`) and have the `TemplateRef` for this Embedded View injected into
* the constructor of the directive using the `TemplateRef` Token. Alternatively you can query for
* the `TemplateRef` from a Component or a Directive via {\@link Query}.
*
* To instantiate Embedded Views based on a Template, use
* {\@link ViewContainerRef#createEmbeddedView}, which will create the View and attach it to the
* View Container.
* \@stable
* @abstract
*/
var TemplateRef = (function () {
function TemplateRef() {
}
/**
* @abstract
* @return {?}
*/
TemplateRef.prototype.elementRef = function () { };
/**
* @abstract
* @param {?} context
* @return {?}
*/
TemplateRef.prototype.createEmbeddedView = function (context) { };
return TemplateRef;
}());
/**
* @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
*/
/**
* Represents a container where one or more Views can be attached.
*
* The container can contain two kinds of Views. Host Views, created by instantiating a
* {\@link Component} via {\@link #createComponent}, and Embedded Views, created by instantiating an
* {\@link TemplateRef Embedded Template} via {\@link #createEmbeddedView}.
*
* The location of the View Container within the containing View is specified by the Anchor
* `element`. Each View Container can have only one Anchor Element and each Anchor Element can only
* have a single View Container.
*
* Root elements of Views attached to this container become siblings of the Anchor Element in
* the Rendered View.
*
* To access a `ViewContainerRef` of an Element, you can either place a {\@link Directive} injected
* with `ViewContainerRef` on the Element, or you obtain it via a {\@link ViewChild} query.
* \@stable
* @abstract
*/
var ViewContainerRef = (function () {
function ViewContainerRef() {
}
/**
* Anchor element that specifies the location of this container in the containing View.
* <!-- TODO: rename to anchorElement -->
* @abstract
* @return {?}
*/
ViewContainerRef.prototype.element = function () { };
/**
* @abstract
* @return {?}
*/
ViewContainerRef.prototype.injector = function () { };
/**
* @abstract
* @return {?}
*/
ViewContainerRef.prototype.parentInjector = function () { };
/**
* Destroys all Views in this container.
* @abstract
* @return {?}
*/
ViewContainerRef.prototype.clear = function () { };
/**
* Returns the {\@link ViewRef} for the View located in this container at the specified index.
* @abstract
* @param {?} index
* @return {?}
*/
ViewContainerRef.prototype.get = function (index) { };
/**
* Returns the number of Views currently attached to this container.
* @abstract
* @return {?}
*/
ViewContainerRef.prototype.length = function () { };
/**
* Instantiates an Embedded View based on the {\@link TemplateRef `templateRef`} and inserts it
* into this container at the specified `index`.
*
* If `index` is not specified, the new View will be inserted as the last View in the container.
*
* Returns the {\@link ViewRef} for the newly created View.
* @abstract
* @template C
* @param {?} templateRef
* @param {?=} context
* @param {?=} index
* @return {?}
*/
ViewContainerRef.prototype.createEmbeddedView = function (templateRef, context, index) { };
/**
* Instantiates a single {\@link Component} and inserts its Host View into this container at the
* specified `index`.
*
* The component is instantiated using its {\@link ComponentFactory} which can be
* obtained via {\@link ComponentFactoryResolver#resolveComponentFactory}.
*
* If `index` is not specified, the new View will be inserted as the last View in the container.
*
* You can optionally specify the {\@link Injector} that will be used as parent for the Component.
*
* Returns the {\@link ComponentRef} of the Host View created for the newly instantiated Component.
* @abstract
* @template C
* @param {?} componentFactory
* @param {?=} index
* @param {?=} injector
* @param {?=} projectableNodes
* @param {?=} ngModule
* @return {?}
*/
ViewContainerRef.prototype.createComponent = function (componentFactory, index, injector, projectableNodes, ngModule) { };
/**
* Inserts a View identified by a {\@link ViewRef} into the container at the specified `index`.
*
* If `index` is not specified, the new View will be inserted as the last View in the container.
*
* Returns the inserted {\@link ViewRef}.
* @abstract
* @param {?} viewRef
* @param {?=} index
* @return {?}
*/
ViewContainerRef.prototype.insert = function (viewRef, index) { };
/**
* Moves a View identified by a {\@link ViewRef} into the container at the specified `index`.
*
* Returns the inserted {\@link ViewRef}.
* @abstract
* @param {?} viewRef
* @param {?} currentIndex
* @return {?}
*/
ViewContainerRef.prototype.move = function (viewRef, currentIndex) { };
/**
* Returns the index of the View, specified via {\@link ViewRef}, within the current container or
* `-1` if this container doesn't contain the View.
* @abstract
* @param {?} viewRef
* @return {?}
*/
ViewContainerRef.prototype.indexOf = function (viewRef) { };
/**
* Destroys a View attached to this container at the specified `index`.
*
* If `index` is not specified, the last View in the container will be removed.
* @abstract
* @param {?=} index
* @return {?}
*/
ViewContainerRef.prototype.remove = function (index) { };
/**
* Use along with {\@link #insert} to move a View within the current container.
*
* If the `index` param is omitted, the last {\@link ViewRef} is detached.
* @abstract
* @param {?=} index
* @return {?}
*/
ViewContainerRef.prototype.detach = function (index) { };
return ViewContainerRef;
}());
/**
* \@stable
* @abstract
*/
var ChangeDetectorRef = (function () {
function ChangeDetectorRef() {
}
/**
* Marks all {\@link ChangeDetectionStrategy#OnPush} ancestors as to be checked.
*
* <!-- TODO: Add a link to a chapter on OnPush components -->
*
* ### Example ([live demo](http://plnkr.co/edit/GC512b?p=preview))
*
* ```typescript
* \@Component({
* selector: 'cmp',
* changeDetection: ChangeDetectionStrategy.OnPush,
* template: `Number of ticks: {{numberOfTicks}}`
* })
* class Cmp {
* numberOfTicks = 0;
*
* constructor(ref: ChangeDetectorRef) {
* setInterval(() => {
* this.numberOfTicks ++
* // the following is required, otherwise the view will not be updated
* this.ref.markForCheck();
* }, 1000);
* }
* }
*
* \@Component({
* selector: 'app',
* changeDetection: ChangeDetectionStrategy.OnPush,
* template: `
* <cmp><cmp>
* `,
* })
* class App {
* }
* ```
* @abstract
* @return {?}
*/
ChangeDetectorRef.prototype.markForCheck = function () { };
/**
* Detaches the change detector from the change detector tree.
*
* The detached change detector will not be checked until it is reattached.
*
* This can also be used in combination with {\@link ChangeDetectorRef#detectChanges} to implement
* local change
* detection checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds. We can do that by detaching
* the component's change detector and doing a local check every five seconds.
*
* ```typescript
* class DataProvider {
* // in a real application the returned data will be different every time
* get data() {
* return [1,2,3,4,5];
* }
* }
*
* \@Component({
* selector: 'giant-list',
* template: `
* <li *ngFor="let d of dataProvider.data">Data {{d}}</lig>
* `,
* })
* class GiantList {
* constructor(private ref: ChangeDetectorRef, private dataProvider:DataProvider) {
* ref.detach();
* setInterval(() => {
* this.ref.detectChanges();
* }, 5000);
* }
* }
*
* \@Component({
* selector: 'app',
* providers: [DataProvider],
* template: `
* <giant-list><giant-list>
* `,
* })
* class App {
* }
* ```
* @abstract
* @return {?}
*/
ChangeDetectorRef.prototype.detach = function () { };
/**
* Checks the change detector and its children.
*
* This can also be used in combination with {\@link ChangeDetectorRef#detach} to implement local
* change detection
* checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine, the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds.
*
* We can do that by detaching the component's change detector and doing a local change detection
* check
* every five seconds.
*
* See {\@link ChangeDetectorRef#detach} for more information.
* @abstract
* @return {?}
*/
ChangeDetectorRef.prototype.detectChanges = function () { };
/**
* Checks the change detector and its children, and throws if any changes are detected.
*
* This is used in development mode to verify that running change detection doesn't introduce
* other changes.
* @abstract
* @return {?}
*/
ChangeDetectorRef.prototype.checkNoChanges = function () { };
/**
* Reattach the change detector to the change detector tree.
*
* This also marks OnPush ancestors as to be checked. This reattached change detector will be
* checked during the next change detection run.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
*
* ### Example ([live demo](http://plnkr.co/edit/aUhZha?p=preview))
*
* The following example creates a component displaying `live` data. The component will detach
* its change detector from the main change detector tree when the component's live property
* is set to false.
*
* ```typescript
* class DataProvider {
* data = 1;
*
* constructor() {
* setInterval(() => {
* this.data = this.data * 2;
* }, 500);
* }
* }
*
* \@Component({
* selector: 'live-data',
* inputs: ['live'],
* template: 'Data: {{dataProvider.data}}'
* })
* class LiveData {
* constructor(private ref: ChangeDetectorRef, private dataProvider:DataProvider) {}
*
* set live(value) {
* if (value)
* this.ref.reattach();
* else
* this.ref.detach();
* }
* }
*
* \@Component({
* selector: 'app',
* providers: [DataProvider],
* template: `
* Live Update: <input type="checkbox" [(ngModel)]="live">
* <live-data [live]="live"><live-data>
* `,
* })
* class App {
* live = true;
* }
* ```
* @abstract
* @return {?}
*/
ChangeDetectorRef.prototype.reattach = function () { };
return ChangeDetectorRef;
}());
/**
* @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
*/
/**
* \@stable
* @abstract
*/
var ViewRef = (function (_super) {
__extends(ViewRef, _super);
function ViewRef() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Destroys the view and all of the data structures associated with it.
* @abstract
* @return {?}
*/
ViewRef.prototype.destroy = function () { };
/**
* @abstract
* @return {?}
*/
ViewRef.prototype.destroyed = function () { };
/**
* @abstract
* @param {?} callback
* @return {?}
*/
ViewRef.prototype.onDestroy = function (callback) { };
return ViewRef;
}(ChangeDetectorRef));
/**
* Represents an Angular View.
*
* <!-- TODO: move the next two paragraphs to the dev guide -->
* A View is a fundamental building block of the application UI. It is the smallest grouping of
* Elements which are created and destroyed together.
*
* Properties of elements in a View can change, but the structure (number and order) of elements in
* a View cannot. Changing the structure of Elements can only be done by inserting, moving or
* removing nested Views via a {\@link ViewContainerRef}. Each View can contain many View Containers.
* <!-- /TODO -->
*
* ### Example
*
* Given this template...
*
* ```
* Count: {{items.length}}
* <ul>
* <li *ngFor="let item of items">{{item}}</li>
* </ul>
* ```
*
* We have two {\@link TemplateRef}s:
*
* Outer {\@link TemplateRef}:
* ```
* Count: {{items.length}}
* <ul>
* <ng-template ngFor let-item [ngForOf]="items"></ng-template>
* </ul>
* ```
*
* Inner {\@link TemplateRef}:
* ```
* <li>{{item}}</li>
* ```
*
* Notice that the original template is broken down into two separate {\@link TemplateRef}s.
*
* The outer/inner {\@link TemplateRef}s are then assembled into views like so:
*
* ```
* <!-- ViewRef: outer-0 -->
* Count: 2
* <ul>
* <ng-template view-container-ref></ng-template>
* <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
* <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
* </ul>
* <!-- /ViewRef: outer-0 -->
* ```
* \@experimental
* @abstract
*/
var EmbeddedViewRef = (function (_super) {
__extends(EmbeddedViewRef, _super);
function EmbeddedViewRef() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @abstract
* @return {?}
*/
EmbeddedViewRef.prototype.context = function () { };
/**
* @abstract
* @return {?}
*/
EmbeddedViewRef.prototype.rootNodes = function () { };
return EmbeddedViewRef;
}(ViewRef));
/**
* @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
*/
// Public API for compiler
/**
* @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
*/
var EventListener = (function () {
/**
* @param {?} name
* @param {?} callback
*/
function EventListener(name, callback) {
this.name = name;
this.callback = callback;
}
;
return EventListener;
}());
/**
* \@experimental All debugging apis are currently experimental.
*/
var DebugNode = (function () {
/**
* @param {?} nativeNode
* @param {?} parent
* @param {?} _debugContext
*/
function DebugNode(nativeNode, parent, _debugContext) {
this._debugContext = _debugContext;
this.nativeNode = nativeNode;
if (parent && parent instanceof DebugElement) {
parent.addChild(this);
}
else {
this.parent = null;
}
this.listeners = [];
}
Object.defineProperty(DebugNode.prototype, "injector", {
/**
* @return {?}
*/
get: function () { return this._debugContext.injector; },
enumerable: true,
configurable: true
});
Object.defineProperty(DebugNode.prototype, "componentInstance", {
/**
* @return {?}
*/
get: function () { return this._debugContext.component; },
enumerable: true,
configurable: true
});
Object.defineProperty(DebugNode.prototype, "context", {
/**
* @return {?}
*/
get: function () { return this._debugContext.context; },
enumerable: true,
configurable: true
});
Object.defineProperty(DebugNode.prototype, "references", {
/**
* @return {?}
*/
get: function () { return this._debugContext.references; },
enumerable: true,
configurable: true
});
Object.defineProperty(DebugNode.prototype, "providerTokens", {
/**
* @return {?}
*/
get: function () { return this._debugContext.providerTokens; },
enumerable: true,
configurable: true
});
Object.defineProperty(DebugNode.prototype, "source", {
/**
* @deprecated since v4
* @return {?}
*/
get: function () { return 'Deprecated since v4'; },
enumerable: true,
configurable: true
});
return DebugNode;
}());
/**
* \@experimental All debugging apis are currently experimental.
*/
var DebugElement = (function (_super) {
__extends(DebugElement, _super);
/**
* @param {?} nativeNode
* @param {?} parent
* @param {?} _debugContext
*/
function DebugElement(nativeNode, parent, _debugContext) {
var _this = _super.call(this, nativeNode, parent, _debugContext) || this;
_this.properties = {};
_this.attributes = {};
_this.classes = {};
_this.styles = {};
_this.childNodes = [];
_this.nativeElement = nativeNode;
return _this;
}
/**
* @param {?} child
* @return {?}
*/
DebugElement.prototype.addChild = function (child) {
if (child) {
this.childNodes.push(child);
child.parent = this;
}
};
/**
* @param {?} child
* @return {?}
*/
DebugElement.prototype.removeChild = function (child) {
var /** @type {?} */ childIndex = this.childNodes.indexOf(child);
if (childIndex !== -1) {
child.parent = null;
this.childNodes.splice(childIndex, 1);
}
};
/**
* @param {?} child
* @param {?} newChildren
* @return {?}
*/
DebugElement.prototype.insertChildrenAfter = function (child, newChildren) {
var _this = this;
var /** @type {?} */ siblingIndex = this.childNodes.indexOf(child);
if (siblingIndex !== -1) {
(_a = this.childNodes).splice.apply(_a, [siblingIndex + 1, 0].concat(newChildren));
newChildren.forEach(function (c) {
if (c.parent) {
c.parent.removeChild(c);
}
c.parent = _this;
});
}
var _a;
};
/**
* @param {?} refChild
* @param {?} newChild
* @return {?}
*/
DebugElement.prototype.insertBefore = function (refChild, newChild) {
var /** @type {?} */ refIndex = this.childNodes.indexOf(refChild);
if (refIndex === -1) {
this.addChild(newChild);
}
else {
if (newChild.parent) {
newChild.parent.removeChild(newChild);
}
newChild.parent = this;
this.childNodes.splice(refIndex, 0, newChild);
}
};
/**
* @param {?} predicate
* @return {?}
*/
DebugElement.prototype.query = function (predicate) {
var /** @type {?} */ results = this.queryAll(predicate);
return results[0] || null;
};
/**
* @param {?} predicate
* @return {?}
*/
DebugElement.prototype.queryAll = function (predicate) {
var /** @type {?} */ matches = [];
_queryElementChildren(this, predicate, matches);
return matches;
};
/**
* @param {?} predicate
* @return {?}
*/
DebugElement.prototype.queryAllNodes = function (predicate) {
var /** @type {?} */ matches = [];
_queryNodeChildren(this, predicate, matches);
return matches;
};
Object.defineProperty(DebugElement.prototype, "children", {
/**
* @return {?}
*/
get: function () {
return (this.childNodes.filter(function (node) { return node instanceof DebugElement; }));
},
enumerable: true,
configurable: true
});
/**
* @param {?} eventName
* @param {?} eventObj
* @return {?}
*/
DebugElement.prototype.triggerEventHandler = function (eventName, eventObj) {
this.listeners.forEach(function (listener) {
if (listener.name == eventName) {
listener.callback(eventObj);
}
});
};
return DebugElement;
}(DebugNode));
/**
* \@experimental
* @param {?} debugEls
* @return {?}
*/
function asNativeElements(debugEls) {
return debugEls.map(function (el) { return el.nativeElement; });
}
/**
* @param {?} element
* @param {?} predicate
* @param {?} matches
* @return {?}
*/
function _queryElementChildren(element, predicate, matches) {
element.childNodes.forEach(function (node) {
if (node instanceof DebugElement) {
if (predicate(node)) {
matches.push(node);
}
_queryElementChildren(node, predicate, matches);
}
});
}
/**
* @param {?} parentNode
* @param {?} predicate
* @param {?} matches
* @return {?}
*/
function _queryNodeChildren(parentNode, predicate, matches) {
if (parentNode instanceof DebugElement) {
parentNode.childNodes.forEach(function (node) {
if (predicate(node)) {
matches.push(node);
}
if (node instanceof DebugElement) {
_queryNodeChildren(node, predicate, matches);
}
});
}
}
// Need to keep the nodes in a global Map so that multiple angular apps are supported.
var _nativeNodeToDebugNode = new Map();
/**
* \@experimental
* @param {?} nativeNode
* @return {?}
*/
function getDebugNode(nativeNode) {
return _nativeNodeToDebugNode.get(nativeNode) || null;
}
/**
* @return {?}
*/
/**
* @param {?} node
* @return {?}
*/
function indexDebugNode(node) {
_nativeNodeToDebugNode.set(node.nativeNode, node);
}
/**
* @param {?} node
* @return {?}
*/
function removeDebugNodeFromIndex(node) {
_nativeNodeToDebugNode.delete(node.nativeNode);
}
/**
* @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
*/
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function devModeEqual(a, b) {
var /** @type {?} */ isListLikeIterableA = isListLikeIterable(a);
var /** @type {?} */ isListLikeIterableB = isListLikeIterable(b);
if (isListLikeIterableA && isListLikeIterableB) {
return areIterablesEqual(a, b, devModeEqual);
}
else {
var /** @type {?} */ isAObject = a && (typeof a === 'object' || typeof a === 'function');
var /** @type {?} */ isBObject = b && (typeof b === 'object' || typeof b === 'function');
if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
return true;
}
else {
return looseIdentical(a, b);
}
}
}
/**
* Indicates that the result of a {\@link Pipe} transformation has changed even though the
* reference
* has not changed.
*
* The wrapped value will be unwrapped by change detection, and the unwrapped value will be stored.
*
* Example:
*
* ```
* if (this._latestValue === this._latestReturnedValue) {
* return this._latestReturnedValue;
* } else {
* this._latestReturnedValue = this._latestValue;
* return WrappedValue.wrap(this._latestValue); // this will force update
* }
* ```
* \@stable
*/
var WrappedValue = (function () {
/**
* @param {?} wrapped
*/
function WrappedValue(wrapped) {
this.wrapped = wrapped;
}
/**
* @param {?} value
* @return {?}
*/
WrappedValue.wrap = function (value) { return new WrappedValue(value); };
return WrappedValue;
}());
/**
* Helper class for unwrapping WrappedValue s
*/
var ValueUnwrapper = (function () {
function ValueUnwrapper() {
this.hasWrappedValue = false;
}
/**
* @param {?} value
* @return {?}
*/
ValueUnwrapper.prototype.unwrap = function (value) {
if (value instanceof WrappedValue) {
this.hasWrappedValue = true;
return value.wrapped;
}
return value;
};
/**
* @return {?}
*/
ValueUnwrapper.prototype.reset = function () { this.hasWrappedValue = false; };
return ValueUnwrapper;
}());
/**
* Represents a basic change from a previous to a new value.
* \@stable
*/
var SimpleChange = (function () {
/**
* @param {?} previousValue
* @param {?} currentValue
* @param {?} firstChange
*/
function SimpleChange(previousValue, currentValue, firstChange) {
this.previousValue = previousValue;
this.currentValue = currentValue;
this.firstChange = firstChange;
}
/**
* Check whether the new value is the first value assigned.
* @return {?}
*/
SimpleChange.prototype.isFirstChange = function () { return this.firstChange; };
return SimpleChange;
}());
/**
* @param {?} obj
* @return {?}
*/
function isListLikeIterable(obj) {
if (!isJsObject(obj))
return false;
return Array.isArray(obj) ||
(!(obj instanceof Map) &&
getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
}
/**
* @param {?} a
* @param {?} b
* @param {?} comparator
* @return {?}
*/
function areIterablesEqual(a, b, comparator) {
var /** @type {?} */ iterator1 = a[getSymbolIterator()]();
var /** @type {?} */ iterator2 = b[getSymbolIterator()]();
while (true) {
var /** @type {?} */ item1 = iterator1.next();
var /** @type {?} */ item2 = iterator2.next();
if (item1.done && item2.done)
return true;
if (item1.done || item2.done)
return false;
if (!comparator(item1.value, item2.value))
return false;
}
}
/**
* @param {?} obj
* @param {?} fn
* @return {?}
*/
function iterateListLike(obj, fn) {
if (Array.isArray(obj)) {
for (var /** @type {?} */ i = 0; i < obj.length; i++) {
fn(obj[i]);
}
}
else {
var /** @type {?} */ iterator = obj[getSymbolIterator()]();
var /** @type {?} */ item = void 0;
while (!((item = iterator.next()).done)) {
fn(item.value);
}
}
}
/**
* @param {?} o
* @return {?}
*/
function isJsObject(o) {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}
/**
* @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
*/
var DefaultIterableDifferFactory = (function () {
function DefaultIterableDifferFactory() {
}
/**
* @param {?} obj
* @return {?}
*/
DefaultIterableDifferFactory.prototype.supports = function (obj) { return isListLikeIterable(obj); };
/**
* @deprecated v4.0.0 - ChangeDetectorRef is not used and is no longer a parameter
* @template V
* @param {?=} cdRefOrTrackBy
* @param {?=} trackByFn
* @return {?}
*/
DefaultIterableDifferFactory.prototype.create = function (cdRefOrTrackBy, trackByFn) {
return new DefaultIterableDiffer(trackByFn || (cdRefOrTrackBy));
};
return DefaultIterableDifferFactory;
}());
var trackByIdentity = function (index, item) { return item; };
/**
* @deprecated v4.0.0 - Should not be part of public API.
*/
var DefaultIterableDiffer = (function () {
/**
* @param {?=} trackByFn
*/
function DefaultIterableDiffer(trackByFn) {
this._length = 0;
this._collection = null;
this._linkedRecords = null;
this._unlinkedRecords = null;
this._previousItHead = null;
this._itHead = null;
this._itTail = null;
this._additionsHead = null;
this._additionsTail = null;
this._movesHead = null;
this._movesTail = null;
this._removalsHead = null;
this._removalsTail = null;
this._identityChangesHead = null;
this._identityChangesTail = null;
this._trackByFn = trackByFn || trackByIdentity;
}
Object.defineProperty(DefaultIterableDiffer.prototype, "collection", {
/**
* @return {?}
*/
get: function () { return this._collection; },
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultIterableDiffer.prototype, "length", {
/**
* @return {?}
*/
get: function () { return this._length; },
enumerable: true,
configurable: true
});
/**
* @param {?} fn
* @return {?}
*/
DefaultIterableDiffer.prototype.forEachItem = function (fn) {
var /** @type {?} */ record;
for (record = this._itHead; record !== null; record = record._next) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultIterableDiffer.prototype.forEachOperation = function (fn) {
var /** @type {?} */ nextIt = this._itHead;
var /** @type {?} */ nextRemove = this._removalsHead;
var /** @type {?} */ addRemoveOffset = 0;
var /** @type {?} */ moveOffsets = null;
while (nextIt || nextRemove) {
// Figure out which is the next record to process
// Order: remove, add, move
var /** @type {?} */ record = !nextRemove ||
nextIt && ((nextIt.currentIndex)) <
getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets) ? ((nextIt)) :
nextRemove;
var /** @type {?} */ adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets);
var /** @type {?} */ currentIndex = record.currentIndex;
// consume the item, and adjust the addRemoveOffset and update moveDistance if necessary
if (record === nextRemove) {
addRemoveOffset--;
nextRemove = nextRemove._nextRemoved;
}
else {
nextIt = ((nextIt))._next;
if (record.previousIndex == null) {
addRemoveOffset++;
}
else {
// INVARIANT: currentIndex < previousIndex
if (!moveOffsets)
moveOffsets = [];
var /** @type {?} */ localMovePreviousIndex = adjPreviousIndex - addRemoveOffset;
var /** @type {?} */ localCurrentIndex = ((currentIndex)) - addRemoveOffset;
if (localMovePreviousIndex != localCurrentIndex) {
for (var /** @type {?} */ i = 0; i < localMovePreviousIndex; i++) {
var /** @type {?} */ offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0);
var /** @type {?} */ index = offset + i;
if (localCurrentIndex <= index && index < localMovePreviousIndex) {
moveOffsets[i] = offset + 1;
}
}
var /** @type {?} */ previousIndex = record.previousIndex;
moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex;
}
}
}
if (adjPreviousIndex !== currentIndex) {
fn(record, adjPreviousIndex, currentIndex);
}
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultIterableDiffer.prototype.forEachPreviousItem = function (fn) {
var /** @type {?} */ record;
for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultIterableDiffer.prototype.forEachAddedItem = function (fn) {
var /** @type {?} */ record;
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultIterableDiffer.prototype.forEachMovedItem = function (fn) {
var /** @type {?} */ record;
for (record = this._movesHead; record !== null; record = record._nextMoved) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultIterableDiffer.prototype.forEachRemovedItem = function (fn) {
var /** @type {?} */ record;
for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultIterableDiffer.prototype.forEachIdentityChange = function (fn) {
var /** @type {?} */ record;
for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) {
fn(record);
}
};
/**
* @param {?} collection
* @return {?}
*/
DefaultIterableDiffer.prototype.diff = function (collection) {
if (collection == null)
collection = [];
if (!isListLikeIterable(collection)) {
throw new Error("Error trying to diff '" + stringify(collection) + "'. Only arrays and iterables are allowed");
}
if (this.check(collection)) {
return this;
}
else {
return null;
}
};
/**
* @return {?}
*/
DefaultIterableDiffer.prototype.onDestroy = function () { };
/**
* @param {?} collection
* @return {?}
*/
DefaultIterableDiffer.prototype.check = function (collection) {
var _this = this;
this._reset();
var /** @type {?} */ record = this._itHead;
var /** @type {?} */ mayBeDirty = false;
var /** @type {?} */ index;
var /** @type {?} */ item;
var /** @type {?} */ itemTrackBy;
if (Array.isArray(collection)) {
this._length = collection.length;
for (var /** @type {?} */ index_1 = 0; index_1 < this._length; index_1++) {
item = collection[index_1];
itemTrackBy = this._trackByFn(index_1, item);
if (record === null || !looseIdentical(record.trackById, itemTrackBy)) {
record = this._mismatch(record, item, itemTrackBy, index_1);
mayBeDirty = true;
}
else {
if (mayBeDirty) {
// TODO(misko): can we limit this to duplicates only?
record = this._verifyReinsertion(record, item, itemTrackBy, index_1);
}
if (!looseIdentical(record.item, item))
this._addIdentityChange(record, item);
}
record = record._next;
}
}
else {
index = 0;
iterateListLike(collection, function (item) {
itemTrackBy = _this._trackByFn(index, item);
if (record === null || !looseIdentical(record.trackById, itemTrackBy)) {
record = _this._mismatch(record, item, itemTrackBy, index);
mayBeDirty = true;
}
else {
if (mayBeDirty) {
// TODO(misko): can we limit this to duplicates only?
record = _this._verifyReinsertion(record, item, itemTrackBy, index);
}
if (!looseIdentical(record.item, item))
_this._addIdentityChange(record, item);
}
record = record._next;
index++;
});
this._length = index;
}
this._truncate(record);
this._collection = collection;
return this.isDirty;
};
Object.defineProperty(DefaultIterableDiffer.prototype, "isDirty", {
/**
* @return {?}
*/
get: function () {
return this._additionsHead !== null || this._movesHead !== null ||
this._removalsHead !== null || this._identityChangesHead !== null;
},
enumerable: true,
configurable: true
});
/**
* Reset the state of the change objects to show no changes. This means set previousKey to
* currentKey, and clear all of the queues (additions, moves, removals).
* Set the previousIndexes of moved and added items to their currentIndexes
* Reset the list of additions, moves and removals
*
* \@internal
* @return {?}
*/
DefaultIterableDiffer.prototype._reset = function () {
if (this.isDirty) {
var /** @type {?} */ record = void 0;
var /** @type {?} */ nextRecord = void 0;
for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {
record._nextPrevious = record._next;
}
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
record.previousIndex = record.currentIndex;
}
this._additionsHead = this._additionsTail = null;
for (record = this._movesHead; record !== null; record = nextRecord) {
record.previousIndex = record.currentIndex;
nextRecord = record._nextMoved;
}
this._movesHead = this._movesTail = null;
this._removalsHead = this._removalsTail = null;
this._identityChangesHead = this._identityChangesTail = null;
}
};
/**
* This is the core function which handles differences between collections.
*
* - `record` is the record which we saw at this position last time. If null then it is a new
* item.
* - `item` is the current item in the collection
* - `index` is the position of the item in the collection
*
* \@internal
* @param {?} record
* @param {?} item
* @param {?} itemTrackBy
* @param {?} index
* @return {?}
*/
DefaultIterableDiffer.prototype._mismatch = function (record, item, itemTrackBy, index) {
// The previous record after which we will append the current one.
var /** @type {?} */ previousRecord;
if (record === null) {
previousRecord = ((this._itTail));
}
else {
previousRecord = ((record._prev));
// Remove the record from the collection since we know it does not match the item.
this._remove(record);
}
// Attempt to see if we have seen the item before.
record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index);
if (record !== null) {
// We have seen this before, we need to move it forward in the collection.
// But first we need to check if identity changed, so we can update in view if necessary
if (!looseIdentical(record.item, item))
this._addIdentityChange(record, item);
this._moveAfter(record, previousRecord, index);
}
else {
// Never seen it, check evicted list.
record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
if (record !== null) {
// It is an item which we have evicted earlier: reinsert it back into the list.
// But first we need to check if identity changed, so we can update in view if necessary
if (!looseIdentical(record.item, item))
this._addIdentityChange(record, item);
this._reinsertAfter(record, previousRecord, index);
}
else {
// It is a new item: add it.
record =
this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index);
}
}
return record;
};
/**
* This check is only needed if an array contains duplicates. (Short circuit of nothing dirty)
*
* Use case: `[a, a]` => `[b, a, a]`
*
* If we did not have this check then the insertion of `b` would:
* 1) evict first `a`
* 2) insert `b` at `0` index.
* 3) leave `a` at index `1` as is. <-- this is wrong!
* 3) reinsert `a` at index 2. <-- this is wrong!
*
* The correct behavior is:
* 1) evict first `a`
* 2) insert `b` at `0` index.
* 3) reinsert `a` at index 1.
* 3) move `a` at from `1` to `2`.
*
*
* Double check that we have not evicted a duplicate item. We need to check if the item type may
* have already been removed:
* The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted
* at the end. Which will show up as the two 'a's switching position. This is incorrect, since a
* better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a'
* at the end.
*
* \@internal
* @param {?} record
* @param {?} item
* @param {?} itemTrackBy
* @param {?} index
* @return {?}
*/
DefaultIterableDiffer.prototype._verifyReinsertion = function (record, item, itemTrackBy, index) {
var /** @type {?} */ reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
if (reinsertRecord !== null) {
record = this._reinsertAfter(reinsertRecord, /** @type {?} */ ((record._prev)), index);
}
else if (record.currentIndex != index) {
record.currentIndex = index;
this._addToMoves(record, index);
}
return record;
};
/**
* Get rid of any excess {\@link IterableChangeRecord_}s from the previous collection
*
* - `record` The first excess {\@link IterableChangeRecord_}.
*
* \@internal
* @param {?} record
* @return {?}
*/
DefaultIterableDiffer.prototype._truncate = function (record) {
// Anything after that needs to be removed;
while (record !== null) {
var /** @type {?} */ nextRecord = record._next;
this._addToRemovals(this._unlink(record));
record = nextRecord;
}
if (this._unlinkedRecords !== null) {
this._unlinkedRecords.clear();
}
if (this._additionsTail !== null) {
this._additionsTail._nextAdded = null;
}
if (this._movesTail !== null) {
this._movesTail._nextMoved = null;
}
if (this._itTail !== null) {
this._itTail._next = null;
}
if (this._removalsTail !== null) {
this._removalsTail._nextRemoved = null;
}
if (this._identityChangesTail !== null) {
this._identityChangesTail._nextIdentityChange = null;
}
};
/**
* \@internal
* @param {?} record
* @param {?} prevRecord
* @param {?} index
* @return {?}
*/
DefaultIterableDiffer.prototype._reinsertAfter = function (record, prevRecord, index) {
if (this._unlinkedRecords !== null) {
this._unlinkedRecords.remove(record);
}
var /** @type {?} */ prev = record._prevRemoved;
var /** @type {?} */ next = record._nextRemoved;
if (prev === null) {
this._removalsHead = next;
}
else {
prev._nextRemoved = next;
}
if (next === null) {
this._removalsTail = prev;
}
else {
next._prevRemoved = prev;
}
this._insertAfter(record, prevRecord, index);
this._addToMoves(record, index);
return record;
};
/**
* \@internal
* @param {?} record
* @param {?} prevRecord
* @param {?} index
* @return {?}
*/
DefaultIterableDiffer.prototype._moveAfter = function (record, prevRecord, index) {
this._unlink(record);
this._insertAfter(record, prevRecord, index);
this._addToMoves(record, index);
return record;
};
/**
* \@internal
* @param {?} record
* @param {?} prevRecord
* @param {?} index
* @return {?}
*/
DefaultIterableDiffer.prototype._addAfter = function (record, prevRecord, index) {
this._insertAfter(record, prevRecord, index);
if (this._additionsTail === null) {
// todo(vicb)
// assert(this._additionsHead === null);
this._additionsTail = this._additionsHead = record;
}
else {
// todo(vicb)
// assert(_additionsTail._nextAdded === null);
// assert(record._nextAdded === null);
this._additionsTail = this._additionsTail._nextAdded = record;
}
return record;
};
/**
* \@internal
* @param {?} record
* @param {?} prevRecord
* @param {?} index
* @return {?}
*/
DefaultIterableDiffer.prototype._insertAfter = function (record, prevRecord, index) {
// todo(vicb)
// assert(record != prevRecord);
// assert(record._next === null);
// assert(record._prev === null);
var /** @type {?} */ next = prevRecord === null ? this._itHead : prevRecord._next;
// todo(vicb)
// assert(next != record);
// assert(prevRecord != record);
record._next = next;
record._prev = prevRecord;
if (next === null) {
this._itTail = record;
}
else {
next._prev = record;
}
if (prevRecord === null) {
this._itHead = record;
}
else {
prevRecord._next = record;
}
if (this._linkedRecords === null) {
this._linkedRecords = new _DuplicateMap();
}
this._linkedRecords.put(record);
record.currentIndex = index;
return record;
};
/**
* \@internal
* @param {?} record
* @return {?}
*/
DefaultIterableDiffer.prototype._remove = function (record) {
return this._addToRemovals(this._unlink(record));
};
/**
* \@internal
* @param {?} record
* @return {?}
*/
DefaultIterableDiffer.prototype._unlink = function (record) {
if (this._linkedRecords !== null) {
this._linkedRecords.remove(record);
}
var /** @type {?} */ prev = record._prev;
var /** @type {?} */ next = record._next;
// todo(vicb)
// assert((record._prev = null) === null);
// assert((record._next = null) === null);
if (prev === null) {
this._itHead = next;
}
else {
prev._next = next;
}
if (next === null) {
this._itTail = prev;
}
else {
next._prev = prev;
}
return record;
};
/**
* \@internal
* @param {?} record
* @param {?} toIndex
* @return {?}
*/
DefaultIterableDiffer.prototype._addToMoves = function (record, toIndex) {
// todo(vicb)
// assert(record._nextMoved === null);
if (record.previousIndex === toIndex) {
return record;
}
if (this._movesTail === null) {
// todo(vicb)
// assert(_movesHead === null);
this._movesTail = this._movesHead = record;
}
else {
// todo(vicb)
// assert(_movesTail._nextMoved === null);
this._movesTail = this._movesTail._nextMoved = record;
}
return record;
};
/**
* @param {?} record
* @return {?}
*/
DefaultIterableDiffer.prototype._addToRemovals = function (record) {
if (this._unlinkedRecords === null) {
this._unlinkedRecords = new _DuplicateMap();
}
this._unlinkedRecords.put(record);
record.currentIndex = null;
record._nextRemoved = null;
if (this._removalsTail === null) {
// todo(vicb)
// assert(_removalsHead === null);
this._removalsTail = this._removalsHead = record;
record._prevRemoved = null;
}
else {
// todo(vicb)
// assert(_removalsTail._nextRemoved === null);
// assert(record._nextRemoved === null);
record._prevRemoved = this._removalsTail;
this._removalsTail = this._removalsTail._nextRemoved = record;
}
return record;
};
/**
* \@internal
* @param {?} record
* @param {?} item
* @return {?}
*/
DefaultIterableDiffer.prototype._addIdentityChange = function (record, item) {
record.item = item;
if (this._identityChangesTail === null) {
this._identityChangesTail = this._identityChangesHead = record;
}
else {
this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record;
}
return record;
};
/**
* @return {?}
*/
DefaultIterableDiffer.prototype.toString = function () {
var /** @type {?} */ list = [];
this.forEachItem(function (record) { return list.push(record); });
var /** @type {?} */ previous = [];
this.forEachPreviousItem(function (record) { return previous.push(record); });
var /** @type {?} */ additions = [];
this.forEachAddedItem(function (record) { return additions.push(record); });
var /** @type {?} */ moves = [];
this.forEachMovedItem(function (record) { return moves.push(record); });
var /** @type {?} */ removals = [];
this.forEachRemovedItem(function (record) { return removals.push(record); });
var /** @type {?} */ identityChanges = [];
this.forEachIdentityChange(function (record) { return identityChanges.push(record); });
return 'collection: ' + list.join(', ') + '\n' +
'previous: ' + previous.join(', ') + '\n' +
'additions: ' + additions.join(', ') + '\n' +
'moves: ' + moves.join(', ') + '\n' +
'removals: ' + removals.join(', ') + '\n' +
'identityChanges: ' + identityChanges.join(', ') + '\n';
};
return DefaultIterableDiffer;
}());
/**
* \@stable
*/
var IterableChangeRecord_ = (function () {
/**
* @param {?} item
* @param {?} trackById
*/
function IterableChangeRecord_(item, trackById) {
this.item = item;
this.trackById = trackById;
this.currentIndex = null;
this.previousIndex = null;
/**
* \@internal
*/
this._nextPrevious = null;
/**
* \@internal
*/
this._prev = null;
/**
* \@internal
*/
this._next = null;
/**
* \@internal
*/
this._prevDup = null;
/**
* \@internal
*/
this._nextDup = null;
/**
* \@internal
*/
this._prevRemoved = null;
/**
* \@internal
*/
this._nextRemoved = null;
/**
* \@internal
*/
this._nextAdded = null;
/**
* \@internal
*/
this._nextMoved = null;
/**
* \@internal
*/
this._nextIdentityChange = null;
}
/**
* @return {?}
*/
IterableChangeRecord_.prototype.toString = function () {
return this.previousIndex === this.currentIndex ? stringify(this.item) :
stringify(this.item) + '[' +
stringify(this.previousIndex) + '->' + stringify(this.currentIndex) + ']';
};
return IterableChangeRecord_;
}());
var _DuplicateItemRecordList = (function () {
function _DuplicateItemRecordList() {
/**
* \@internal
*/
this._head = null;
/**
* \@internal
*/
this._tail = null;
}
/**
* Append the record to the list of duplicates.
*
* Note: by design all records in the list of duplicates hold the same value in record.item.
* @param {?} record
* @return {?}
*/
_DuplicateItemRecordList.prototype.add = function (record) {
if (this._head === null) {
this._head = this._tail = record;
record._nextDup = null;
record._prevDup = null;
}
else {
((
// todo(vicb)
// assert(record.item == _head.item ||
// record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN);
this._tail))._nextDup = record;
record._prevDup = this._tail;
record._nextDup = null;
this._tail = record;
}
};
/**
* @param {?} trackById
* @param {?} afterIndex
* @return {?}
*/
_DuplicateItemRecordList.prototype.get = function (trackById, afterIndex) {
var /** @type {?} */ record;
for (record = this._head; record !== null; record = record._nextDup) {
if ((afterIndex === null || afterIndex < record.currentIndex) &&
looseIdentical(record.trackById, trackById)) {
return record;
}
}
return null;
};
/**
* Remove one {\@link IterableChangeRecord_} from the list of duplicates.
*
* Returns whether the list of duplicates is empty.
* @param {?} record
* @return {?}
*/
_DuplicateItemRecordList.prototype.remove = function (record) {
// todo(vicb)
// assert(() {
// // verify that the record being removed is in the list.
// for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) {
// if (identical(cursor, record)) return true;
// }
// return false;
//});
var /** @type {?} */ prev = record._prevDup;
var /** @type {?} */ next = record._nextDup;
if (prev === null) {
this._head = next;
}
else {
prev._nextDup = next;
}
if (next === null) {
this._tail = prev;
}
else {
next._prevDup = prev;
}
return this._head === null;
};
return _DuplicateItemRecordList;
}());
var _DuplicateMap = (function () {
function _DuplicateMap() {
this.map = new Map();
}
/**
* @param {?} record
* @return {?}
*/
_DuplicateMap.prototype.put = function (record) {
var /** @type {?} */ key = record.trackById;
var /** @type {?} */ duplicates = this.map.get(key);
if (!duplicates) {
duplicates = new _DuplicateItemRecordList();
this.map.set(key, duplicates);
}
duplicates.add(record);
};
/**
* Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we
* have already iterated over, we use the afterIndex to pretend it is not there.
*
* Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we
* have any more `a`s needs to return the last `a` not the first or second.
* @param {?} trackById
* @param {?} afterIndex
* @return {?}
*/
_DuplicateMap.prototype.get = function (trackById, afterIndex) {
var /** @type {?} */ key = trackById;
var /** @type {?} */ recordList = this.map.get(key);
return recordList ? recordList.get(trackById, afterIndex) : null;
};
/**
* Removes a {\@link IterableChangeRecord_} from the list of duplicates.
*
* The list of duplicates also is removed from the map if it gets empty.
* @param {?} record
* @return {?}
*/
_DuplicateMap.prototype.remove = function (record) {
var /** @type {?} */ key = record.trackById;
var /** @type {?} */ recordList = ((this.map.get(key)));
// Remove the list of duplicates when it gets empty
if (recordList.remove(record)) {
this.map.delete(key);
}
return record;
};
Object.defineProperty(_DuplicateMap.prototype, "isEmpty", {
/**
* @return {?}
*/
get: function () { return this.map.size === 0; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
_DuplicateMap.prototype.clear = function () { this.map.clear(); };
/**
* @return {?}
*/
_DuplicateMap.prototype.toString = function () { return '_DuplicateMap(' + stringify(this.map) + ')'; };
return _DuplicateMap;
}());
/**
* @param {?} item
* @param {?} addRemoveOffset
* @param {?} moveOffsets
* @return {?}
*/
function getPreviousIndex(item, addRemoveOffset, moveOffsets) {
var /** @type {?} */ previousIndex = item.previousIndex;
if (previousIndex === null)
return previousIndex;
var /** @type {?} */ moveOffset = 0;
if (moveOffsets && previousIndex < moveOffsets.length) {
moveOffset = moveOffsets[previousIndex];
}
return previousIndex + addRemoveOffset + moveOffset;
}
/**
* @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
*/
var DefaultKeyValueDifferFactory = (function () {
function DefaultKeyValueDifferFactory() {
}
/**
* @param {?} obj
* @return {?}
*/
DefaultKeyValueDifferFactory.prototype.supports = function (obj) { return obj instanceof Map || isJsObject(obj); };
/**
* @deprecated v4.0.0 - ChangeDetectorRef is not used and is no longer a parameter
* @template K, V
* @param {?=} cd
* @return {?}
*/
DefaultKeyValueDifferFactory.prototype.create = function (cd) {
return new DefaultKeyValueDiffer();
};
return DefaultKeyValueDifferFactory;
}());
var DefaultKeyValueDiffer = (function () {
function DefaultKeyValueDiffer() {
this._records = new Map();
this._mapHead = null;
this._appendAfter = null;
this._previousMapHead = null;
this._changesHead = null;
this._changesTail = null;
this._additionsHead = null;
this._additionsTail = null;
this._removalsHead = null;
this._removalsTail = null;
}
Object.defineProperty(DefaultKeyValueDiffer.prototype, "isDirty", {
/**
* @return {?}
*/
get: function () {
return this._additionsHead !== null || this._changesHead !== null ||
this._removalsHead !== null;
},
enumerable: true,
configurable: true
});
/**
* @param {?} fn
* @return {?}
*/
DefaultKeyValueDiffer.prototype.forEachItem = function (fn) {
var /** @type {?} */ record;
for (record = this._mapHead; record !== null; record = record._next) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultKeyValueDiffer.prototype.forEachPreviousItem = function (fn) {
var /** @type {?} */ record;
for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultKeyValueDiffer.prototype.forEachChangedItem = function (fn) {
var /** @type {?} */ record;
for (record = this._changesHead; record !== null; record = record._nextChanged) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultKeyValueDiffer.prototype.forEachAddedItem = function (fn) {
var /** @type {?} */ record;
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
fn(record);
}
};
/**
* @param {?} fn
* @return {?}
*/
DefaultKeyValueDiffer.prototype.forEachRemovedItem = function (fn) {
var /** @type {?} */ record;
for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
fn(record);
}
};
/**
* @param {?=} map
* @return {?}
*/
DefaultKeyValueDiffer.prototype.diff = function (map) {
if (!map) {
map = new Map();
}
else if (!(map instanceof Map || isJsObject(map))) {
throw new Error("Error trying to diff '" + stringify(map) + "'. Only maps and objects are allowed");
}
return this.check(map) ? this : null;
};
/**
* @return {?}
*/
DefaultKeyValueDiffer.prototype.onDestroy = function () { };
/**
* Check the current state of the map vs the previous.
* The algorithm is optimised for when the keys do no change.
* @param {?} map
* @return {?}
*/
DefaultKeyValueDiffer.prototype.check = function (map) {
var _this = this;
this._reset();
var /** @type {?} */ insertBefore = this._mapHead;
this._appendAfter = null;
this._forEach(map, function (value, key) {
if (insertBefore && insertBefore.key === key) {
_this._maybeAddToChanges(insertBefore, value);
_this._appendAfter = insertBefore;
insertBefore = insertBefore._next;
}
else {
var /** @type {?} */ record = _this._getOrCreateRecordForKey(key, value);
insertBefore = _this._insertBeforeOrAppend(insertBefore, record);
}
});
// Items remaining at the end of the list have been deleted
if (insertBefore) {
if (insertBefore._prev) {
insertBefore._prev._next = null;
}
this._removalsHead = insertBefore;
for (var /** @type {?} */ record = insertBefore; record !== null; record = record._nextRemoved) {
if (record === this._mapHead) {
this._mapHead = null;
}
this._records.delete(record.key);
record._nextRemoved = record._next;
record.previousValue = record.currentValue;
record.currentValue = null;
record._prev = null;
record._next = null;
}
}
// Make sure tails have no next records from previous runs
if (this._changesTail)
this._changesTail._nextChanged = null;
if (this._additionsTail)
this._additionsTail._nextAdded = null;
return this.isDirty;
};
/**
* Inserts a record before `before` or append at the end of the list when `before` is null.
*
* Notes:
* - This method appends at `this._appendAfter`,
* - This method updates `this._appendAfter`,
* - The return value is the new value for the insertion pointer.
* @param {?} before
* @param {?} record
* @return {?}
*/
DefaultKeyValueDiffer.prototype._insertBeforeOrAppend = function (before, record) {
if (before) {
var /** @type {?} */ prev = before._prev;
record._next = before;
record._prev = prev;
before._prev = record;
if (prev) {
prev._next = record;
}
if (before === this._mapHead) {
this._mapHead = record;
}
this._appendAfter = before;
return before;
}
if (this._appendAfter) {
this._appendAfter._next = record;
record._prev = this._appendAfter;
}
else {
this._mapHead = record;
}
this._appendAfter = record;
return null;
};
/**
* @param {?} key
* @param {?} value
* @return {?}
*/
DefaultKeyValueDiffer.prototype._getOrCreateRecordForKey = function (key, value) {
if (this._records.has(key)) {
var /** @type {?} */ record_1 = ((this._records.get(key)));
this._maybeAddToChanges(record_1, value);
var /** @type {?} */ prev = record_1._prev;
var /** @type {?} */ next = record_1._next;
if (prev) {
prev._next = next;
}
if (next) {
next._prev = prev;
}
record_1._next = null;
record_1._prev = null;
return record_1;
}
var /** @type {?} */ record = new KeyValueChangeRecord_(key);
this._records.set(key, record);
record.currentValue = value;
this._addToAdditions(record);
return record;
};
/**
* \@internal
* @return {?}
*/
DefaultKeyValueDiffer.prototype._reset = function () {
if (this.isDirty) {
var /** @type {?} */ record = void 0;
// let `_previousMapHead` contain the state of the map before the changes
this._previousMapHead = this._mapHead;
for (record = this._previousMapHead; record !== null; record = record._next) {
record._nextPrevious = record._next;
}
// Update `record.previousValue` with the value of the item before the changes
// We need to update all changed items (that's those which have been added and changed)
for (record = this._changesHead; record !== null; record = record._nextChanged) {
record.previousValue = record.currentValue;
}
for (record = this._additionsHead; record != null; record = record._nextAdded) {
record.previousValue = record.currentValue;
}
this._changesHead = this._changesTail = null;
this._additionsHead = this._additionsTail = null;
this._removalsHead = null;
}
};
/**
* @param {?} record
* @param {?} newValue
* @return {?}
*/
DefaultKeyValueDiffer.prototype._maybeAddToChanges = function (record, newValue) {
if (!looseIdentical(newValue, record.currentValue)) {
record.previousValue = record.currentValue;
record.currentValue = newValue;
this._addToChanges(record);
}
};
/**
* @param {?} record
* @return {?}
*/
DefaultKeyValueDiffer.prototype._addToAdditions = function (record) {
if (this._additionsHead === null) {
this._additionsHead = this._additionsTail = record;
}
else {
((this._additionsTail))._nextAdded = record;
this._additionsTail = record;
}
};
/**
* @param {?} record
* @return {?}
*/
DefaultKeyValueDiffer.prototype._addToChanges = function (record) {
if (this._changesHead === null) {
this._changesHead = this._changesTail = record;
}
else {
((this._changesTail))._nextChanged = record;
this._changesTail = record;
}
};
/**
* @return {?}
*/
DefaultKeyValueDiffer.prototype.toString = function () {
var /** @type {?} */ items = [];
var /** @type {?} */ previous = [];
var /** @type {?} */ changes = [];
var /** @type {?} */ additions = [];
var /** @type {?} */ removals = [];
this.forEachItem(function (r) { return items.push(stringify(r)); });
this.forEachPreviousItem(function (r) { return previous.push(stringify(r)); });
this.forEachChangedItem(function (r) { return changes.push(stringify(r)); });
this.forEachAddedItem(function (r) { return additions.push(stringify(r)); });
this.forEachRemovedItem(function (r) { return removals.push(stringify(r)); });
return 'map: ' + items.join(', ') + '\n' +
'previous: ' + previous.join(', ') + '\n' +
'additions: ' + additions.join(', ') + '\n' +
'changes: ' + changes.join(', ') + '\n' +
'removals: ' + removals.join(', ') + '\n';
};
/**
* \@internal
* @template K, V
* @param {?} obj
* @param {?} fn
* @return {?}
*/
DefaultKeyValueDiffer.prototype._forEach = function (obj, fn) {
if (obj instanceof Map) {
obj.forEach(fn);
}
else {
Object.keys(obj).forEach(function (k) { return fn(obj[k], k); });
}
};
return DefaultKeyValueDiffer;
}());
/**
* \@stable
*/
var KeyValueChangeRecord_ = (function () {
/**
* @param {?} key
*/
function KeyValueChangeRecord_(key) {
this.key = key;
this.previousValue = null;
this.currentValue = null;
/**
* \@internal
*/
this._nextPrevious = null;
/**
* \@internal
*/
this._next = null;
/**
* \@internal
*/
this._prev = null;
/**
* \@internal
*/
this._nextAdded = null;
/**
* \@internal
*/
this._nextRemoved = null;
/**
* \@internal
*/
this._nextChanged = null;
}
/**
* @return {?}
*/
KeyValueChangeRecord_.prototype.toString = function () {
return looseIdentical(this.previousValue, this.currentValue) ?
stringify(this.key) :
(stringify(this.key) + '[' + stringify(this.previousValue) + '->' +
stringify(this.currentValue) + ']');
};
return KeyValueChangeRecord_;
}());
/**
* @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
*/
/**
* A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
* \@stable
*/
var IterableDiffers = (function () {
/**
* @param {?} factories
*/
function IterableDiffers(factories) {
this.factories = factories;
}
/**
* @param {?} factories
* @param {?=} parent
* @return {?}
*/
IterableDiffers.create = function (factories, parent) {
if (parent != null) {
var /** @type {?} */ copied = parent.factories.slice();
factories = factories.concat(copied);
return new IterableDiffers(factories);
}
else {
return new IterableDiffers(factories);
}
};
/**
* Takes an array of {\@link IterableDifferFactory} and returns a provider used to extend the
* inherited {\@link IterableDiffers} instance with the provided factories and return a new
* {\@link IterableDiffers} instance.
*
* The following example shows how to extend an existing list of factories,
* which will only be applied to the injector for this component and its children.
* This step is all that's required to make a new {\@link IterableDiffer} available.
*
* ### Example
*
* ```
* \@Component({
* viewProviders: [
* IterableDiffers.extend([new ImmutableListDiffer()])
* ]
* })
* ```
* @param {?} factories
* @return {?}
*/
IterableDiffers.extend = function (factories) {
return {
provide: IterableDiffers,
useFactory: function (parent) {
if (!parent) {
// Typically would occur when calling IterableDiffers.extend inside of dependencies passed
// to
// bootstrap(), which would override default pipes instead of extending them.
throw new Error('Cannot extend IterableDiffers without a parent injector');
}
return IterableDiffers.create(factories, parent);
},
// Dependency technically isn't optional, but we can provide a better error message this way.
deps: [[IterableDiffers, new SkipSelf(), new Optional()]]
};
};
/**
* @param {?} iterable
* @return {?}
*/
IterableDiffers.prototype.find = function (iterable) {
var /** @type {?} */ factory = this.factories.find(function (f) { return f.supports(iterable); });
if (factory != null) {
return factory;
}
else {
throw new Error("Cannot find a differ supporting object '" + iterable + "' of type '" + getTypeNameForDebugging(iterable) + "'");
}
};
return IterableDiffers;
}());
/**
* @param {?} type
* @return {?}
*/
function getTypeNameForDebugging(type) {
return type['name'] || typeof type;
}
/**
* @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
*/
/**
* A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
* \@stable
*/
var KeyValueDiffers = (function () {
/**
* @param {?} factories
*/
function KeyValueDiffers(factories) {
this.factories = factories;
}
/**
* @template S
* @param {?} factories
* @param {?=} parent
* @return {?}
*/
KeyValueDiffers.create = function (factories, parent) {
if (parent) {
var /** @type {?} */ copied = parent.factories.slice();
factories = factories.concat(copied);
}
return new KeyValueDiffers(factories);
};
/**
* Takes an array of {\@link KeyValueDifferFactory} and returns a provider used to extend the
* inherited {\@link KeyValueDiffers} instance with the provided factories and return a new
* {\@link KeyValueDiffers} instance.
*
* The following example shows how to extend an existing list of factories,
* which will only be applied to the injector for this component and its children.
* This step is all that's required to make a new {\@link KeyValueDiffer} available.
*
* ### Example
*
* ```
* \@Component({
* viewProviders: [
* KeyValueDiffers.extend([new ImmutableMapDiffer()])
* ]
* })
* ```
* @template S
* @param {?} factories
* @return {?}
*/
KeyValueDiffers.extend = function (factories) {
return {
provide: KeyValueDiffers,
useFactory: function (parent) {
if (!parent) {
// Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
// to bootstrap(), which would override default pipes instead of extending them.
throw new Error('Cannot extend KeyValueDiffers without a parent injector');
}
return KeyValueDiffers.create(factories, parent);
},
// Dependency technically isn't optional, but we can provide a better error message this way.
deps: [[KeyValueDiffers, new SkipSelf(), new Optional()]]
};
};
/**
* @param {?} kv
* @return {?}
*/
KeyValueDiffers.prototype.find = function (kv) {
var /** @type {?} */ factory = this.factories.find(function (f) { return f.supports(kv); });
if (factory) {
return factory;
}
throw new Error("Cannot find a differ supporting object '" + kv + "'");
};
return KeyValueDiffers;
}());
/**
* @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
*/
/**
* Structural diffing for `Object`s and `Map`s.
*/
var keyValDiff = [new DefaultKeyValueDifferFactory()];
/**
* Structural diffing for `Iterable` types such as `Array`s.
*/
var iterableDiff = [new DefaultIterableDifferFactory()];
var defaultIterableDiffers = new IterableDiffers(iterableDiff);
var defaultKeyValueDiffers = new KeyValueDiffers(keyValDiff);
/**
* @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
*/
/**
* @module
* @description
* Change detection enables data binding in Angular.
*/
/**
* @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
*/
/**
* @return {?}
*/
function _reflector() {
return reflector;
}
var _CORE_PLATFORM_PROVIDERS = [
// Set a default platform name for platforms that don't set it explicitly.
{ provide: PLATFORM_ID, useValue: 'unknown' },
PlatformRef_,
{ provide: PlatformRef, useExisting: PlatformRef_ },
{ provide: Reflector, useFactory: _reflector, deps: [] },
{ provide: ReflectorReader, useExisting: Reflector },
TestabilityRegistry,
Console,
];
/**
* This platform has to be included in any other platform
*
* \@experimental
*/
var platformCore = createPlatformFactory(null, 'core', _CORE_PLATFORM_PROVIDERS);
/**
* @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
*/
/**
* \@experimental i18n support is experimental.
*/
var LOCALE_ID = new InjectionToken('LocaleId');
/**
* \@experimental i18n support is experimental.
*/
var TRANSLATIONS = new InjectionToken('Translations');
/**
* \@experimental i18n support is experimental.
*/
var TRANSLATIONS_FORMAT = new InjectionToken('TranslationsFormat');
var MissingTranslationStrategy = {};
MissingTranslationStrategy.Error = 0;
MissingTranslationStrategy.Warning = 1;
MissingTranslationStrategy.Ignore = 2;
MissingTranslationStrategy[MissingTranslationStrategy.Error] = "Error";
MissingTranslationStrategy[MissingTranslationStrategy.Warning] = "Warning";
MissingTranslationStrategy[MissingTranslationStrategy.Ignore] = "Ignore";
var SecurityContext = {};
SecurityContext.NONE = 0;
SecurityContext.HTML = 1;
SecurityContext.STYLE = 2;
SecurityContext.SCRIPT = 3;
SecurityContext.URL = 4;
SecurityContext.RESOURCE_URL = 5;
SecurityContext[SecurityContext.NONE] = "NONE";
SecurityContext[SecurityContext.HTML] = "HTML";
SecurityContext[SecurityContext.STYLE] = "STYLE";
SecurityContext[SecurityContext.SCRIPT] = "SCRIPT";
SecurityContext[SecurityContext.URL] = "URL";
SecurityContext[SecurityContext.RESOURCE_URL] = "RESOURCE_URL";
/**
* Sanitizer is used by the views to sanitize potentially dangerous values.
*
* \@stable
* @abstract
*/
var Sanitizer = (function () {
function Sanitizer() {
}
/**
* @abstract
* @param {?} context
* @param {?} value
* @return {?}
*/
Sanitizer.prototype.sanitize = function (context, value) { };
return Sanitizer;
}());
/**
* @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
*/
/**
* Node instance data.
*
* We have a separate type per NodeType to save memory
* (TextData | ElementData | ProviderData | PureExpressionData | QueryList<any>)
*
* To keep our code monomorphic,
* we prohibit using `NodeData` directly but enforce the use of accessors (`asElementData`, ...).
* This way, no usage site can get a `NodeData` from view.nodes and then use it for different
* purposes.
*/
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asTextData(view, index) {
return (view.nodes[index]);
}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asElementData(view, index) {
return (view.nodes[index]);
}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asProviderData(view, index) {
return (view.nodes[index]);
}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asPureExpressionData(view, index) {
return (view.nodes[index]);
}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asQueryList(view, index) {
return (view.nodes[index]);
}
/**
* @abstract
*/
var DebugContext = (function () {
function DebugContext() {
}
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.view = function () { };
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.nodeIndex = function () { };
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.injector = function () { };
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.component = function () { };
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.providerTokens = function () { };
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.references = function () { };
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.context = function () { };
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.componentRenderElement = function () { };
/**
* @abstract
* @return {?}
*/
DebugContext.prototype.renderNode = function () { };
/**
* @abstract
* @param {?} console
* @param {...?} values
* @return {?}
*/
DebugContext.prototype.logError = function (console) {
var values = [];
for (var _i = 1; _i < arguments.length; _i++) {
values[_i - 1] = arguments[_i];
}
};
return DebugContext;
}());
/**
* This object is used to prevent cycles in the source files and to have a place where
* debug mode can hook it. It is lazily filled when `isDevMode` is known.
*/
var Services = {
setCurrentNode: /** @type {?} */ ((undefined)),
createRootView: /** @type {?} */ ((undefined)),
createEmbeddedView: /** @type {?} */ ((undefined)),
checkAndUpdateView: /** @type {?} */ ((undefined)),
checkNoChangesView: /** @type {?} */ ((undefined)),
destroyView: /** @type {?} */ ((undefined)),
resolveDep: /** @type {?} */ ((undefined)),
createDebugContext: /** @type {?} */ ((undefined)),
handleEvent: /** @type {?} */ ((undefined)),
updateDirectives: /** @type {?} */ ((undefined)),
updateRenderer: /** @type {?} */ ((undefined)),
dirtyParentQueries: /** @type {?} */ ((undefined)),
};
/**
* @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
*/
/**
* @param {?} context
* @param {?} oldValue
* @param {?} currValue
* @param {?} isFirstCheck
* @return {?}
*/
function expressionChangedAfterItHasBeenCheckedError(context, oldValue, currValue, isFirstCheck) {
var /** @type {?} */ msg = "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '" + oldValue + "'. Current value: '" + currValue + "'.";
if (isFirstCheck) {
msg +=
" It seems like the view has been created after its parent and its children have been dirty checked." +
" Has it been created in a change detection hook ?";
}
return viewDebugError(msg, context);
}
/**
* @param {?} err
* @param {?} context
* @return {?}
*/
function viewWrappedDebugError(err, context) {
if (!(err instanceof Error)) {
// errors that are not Error instances don't have a stack,
// so it is ok to wrap them into a new Error object...
err = new Error(err.toString());
}
_addDebugContext(err, context);
return err;
}
/**
* @param {?} msg
* @param {?} context
* @return {?}
*/
function viewDebugError(msg, context) {
var /** @type {?} */ err = new Error(msg);
_addDebugContext(err, context);
return err;
}
/**
* @param {?} err
* @param {?} context
* @return {?}
*/
function _addDebugContext(err, context) {
((err))[ERROR_DEBUG_CONTEXT] = context;
((err))[ERROR_LOGGER] = context.logError.bind(context);
}
/**
* @param {?} err
* @return {?}
*/
function isViewDebugError(err) {
return !!getDebugContext(err);
}
/**
* @param {?} action
* @return {?}
*/
function viewDestroyedError(action) {
return new Error("ViewDestroyedError: Attempt to use a destroyed view: " + action);
}
/**
* @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
*/
var NOOP = function () { };
var _tokenKeyCache = new Map();
/**
* @param {?} token
* @return {?}
*/
function tokenKey(token) {
var /** @type {?} */ key = _tokenKeyCache.get(token);
if (!key) {
key = stringify(token) + '_' + _tokenKeyCache.size;
_tokenKeyCache.set(token, key);
}
return key;
}
/**
* @param {?} view
* @param {?} nodeIdx
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function unwrapValue(view, nodeIdx, bindingIdx, value) {
if (value instanceof WrappedValue) {
value = value.wrapped;
var /** @type {?} */ globalBindingIdx = view.def.nodes[nodeIdx].bindingIndex + bindingIdx;
var /** @type {?} */ oldValue = view.oldValues[globalBindingIdx];
if (oldValue instanceof WrappedValue) {
oldValue = oldValue.wrapped;
}
view.oldValues[globalBindingIdx] = new WrappedValue(oldValue);
}
return value;
}
var UNDEFINED_RENDERER_TYPE_ID = '$$undefined';
var EMPTY_RENDERER_TYPE_ID = '$$empty';
/**
* @param {?} values
* @return {?}
*/
function createRendererType2(values) {
return {
id: UNDEFINED_RENDERER_TYPE_ID,
styles: values.styles,
encapsulation: values.encapsulation,
data: values.data
};
}
var _renderCompCount = 0;
/**
* @param {?=} type
* @return {?}
*/
function resolveRendererType2(type) {
if (type && type.id === UNDEFINED_RENDERER_TYPE_ID) {
// first time we see this RendererType2. Initialize it...
var /** @type {?} */ isFilled = ((type.encapsulation != null && type.encapsulation !== ViewEncapsulation.None) ||
type.styles.length || Object.keys(type.data).length);
if (isFilled) {
type.id = "c" + _renderCompCount++;
}
else {
type.id = EMPTY_RENDERER_TYPE_ID;
}
}
if (type && type.id === EMPTY_RENDERER_TYPE_ID) {
type = null;
}
return type || null;
}
/**
* @param {?} view
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function checkBinding(view, def, bindingIdx, value) {
var /** @type {?} */ oldValues = view.oldValues;
if ((view.state & 2 /* FirstCheck */) ||
!looseIdentical(oldValues[def.bindingIndex + bindingIdx], value)) {
return true;
}
return false;
}
/**
* @param {?} view
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function checkAndUpdateBinding(view, def, bindingIdx, value) {
if (checkBinding(view, def, bindingIdx, value)) {
view.oldValues[def.bindingIndex + bindingIdx] = value;
return true;
}
return false;
}
/**
* @param {?} view
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function checkBindingNoChanges(view, def, bindingIdx, value) {
var /** @type {?} */ oldValue = view.oldValues[def.bindingIndex + bindingIdx];
if ((view.state & 1 /* BeforeFirstCheck */) || !devModeEqual(oldValue, value)) {
throw expressionChangedAfterItHasBeenCheckedError(Services.createDebugContext(view, def.index), oldValue, value, (view.state & 1 /* BeforeFirstCheck */) !== 0);
}
}
/**
* @param {?} view
* @return {?}
*/
function markParentViewsForCheck(view) {
var /** @type {?} */ currView = view;
while (currView) {
if (currView.def.flags & 2 /* OnPush */) {
currView.state |= 8 /* ChecksEnabled */;
}
currView = currView.viewContainerParent || currView.parent;
}
}
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} eventName
* @param {?} event
* @return {?}
*/
function dispatchEvent(view, nodeIndex, eventName, event) {
var /** @type {?} */ nodeDef = view.def.nodes[nodeIndex];
var /** @type {?} */ startView = nodeDef.flags & 16777216 /* ComponentView */ ? asElementData(view, nodeIndex).componentView : view;
markParentViewsForCheck(startView);
return Services.handleEvent(view, nodeIndex, eventName, event);
}
/**
* @param {?} view
* @return {?}
*/
function declaredViewContainer(view) {
if (view.parent) {
var /** @type {?} */ parentView = view.parent;
return asElementData(parentView, /** @type {?} */ ((view.parentNodeDef)).index);
}
return null;
}
/**
* for component views, this is the host element.
* for embedded views, this is the index of the parent node
* that contains the view container.
* @param {?} view
* @return {?}
*/
function viewParentEl(view) {
var /** @type {?} */ parentView = view.parent;
if (parentView) {
return ((view.parentNodeDef)).parent;
}
else {
return null;
}
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function renderNode(view, def) {
switch (def.flags & 100673535 /* Types */) {
case 1 /* TypeElement */:
return asElementData(view, def.index).renderElement;
case 2 /* TypeText */:
return asTextData(view, def.index).renderText;
}
}
/**
* @param {?} target
* @param {?} name
* @return {?}
*/
function elementEventFullName(target, name) {
return target ? target + ":" + name : name;
}
/**
* @param {?} view
* @return {?}
*/
function isComponentView(view) {
return !!view.parent && !!(((view.parentNodeDef)).flags & 16384 /* Component */);
}
/**
* @param {?} view
* @return {?}
*/
function isEmbeddedView(view) {
return !!view.parent && !(((view.parentNodeDef)).flags & 16384 /* Component */);
}
/**
* @param {?} queryId
* @return {?}
*/
function filterQueryId(queryId) {
return 1 << (queryId % 32);
}
/**
* @param {?} matchedQueriesDsl
* @return {?}
*/
function splitMatchedQueriesDsl(matchedQueriesDsl) {
var /** @type {?} */ matchedQueries = {};
var /** @type {?} */ matchedQueryIds = 0;
var /** @type {?} */ references = {};
if (matchedQueriesDsl) {
matchedQueriesDsl.forEach(function (_a) {
var queryId = _a[0], valueType = _a[1];
if (typeof queryId === 'number') {
matchedQueries[queryId] = valueType;
matchedQueryIds |= filterQueryId(queryId);
}
else {
references[queryId] = valueType;
}
});
}
return { matchedQueries: matchedQueries, references: references, matchedQueryIds: matchedQueryIds };
}
/**
* @param {?} view
* @param {?} renderHost
* @param {?} def
* @return {?}
*/
function getParentRenderElement(view, renderHost, def) {
var /** @type {?} */ renderParent = def.renderParent;
if (renderParent) {
if ((renderParent.flags & 1 /* TypeElement */) === 0 ||
(renderParent.flags & 16777216 /* ComponentView */) === 0 ||
(((renderParent.element)).componentRendererType && ((((renderParent.element)).componentRendererType)).encapsulation ===
ViewEncapsulation.Native)) {
// only children of non components, or children of components with native encapsulation should
// be attached.
return asElementData(view, /** @type {?} */ ((def.renderParent)).index).renderElement;
}
}
else {
return renderHost;
}
}
var VIEW_DEFINITION_CACHE = new WeakMap();
/**
* @param {?} factory
* @return {?}
*/
function resolveViewDefinition(factory) {
var /** @type {?} */ value = ((VIEW_DEFINITION_CACHE.get(factory)));
if (!value) {
value = factory(function () { return NOOP; });
value.factory = factory;
VIEW_DEFINITION_CACHE.set(factory, value);
}
return value;
}
/**
* @param {?} view
* @return {?}
*/
function rootRenderNodes(view) {
var /** @type {?} */ renderNodes = [];
visitRootRenderNodes(view, 0 /* Collect */, undefined, undefined, renderNodes);
return renderNodes;
}
/**
* @param {?} view
* @param {?} action
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function visitRootRenderNodes(view, action, parentNode, nextSibling, target) {
// We need to re-compute the parent node in case the nodes have been moved around manually
if (action === 3 /* RemoveChild */) {
parentNode = view.renderer.parentNode(renderNode(view, /** @type {?} */ ((view.def.lastRenderRootNode))));
}
visitSiblingRenderNodes(view, action, 0, view.def.nodes.length - 1, parentNode, nextSibling, target);
}
/**
* @param {?} view
* @param {?} action
* @param {?} startIndex
* @param {?} endIndex
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function visitSiblingRenderNodes(view, action, startIndex, endIndex, parentNode, nextSibling, target) {
for (var /** @type {?} */ i = startIndex; i <= endIndex; i++) {
var /** @type {?} */ nodeDef = view.def.nodes[i];
if (nodeDef.flags & (1 /* TypeElement */ | 2 /* TypeText */ | 4 /* TypeNgContent */)) {
visitRenderNode(view, nodeDef, action, parentNode, nextSibling, target);
}
// jump to next sibling
i += nodeDef.childCount;
}
}
/**
* @param {?} view
* @param {?} ngContentIndex
* @param {?} action
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function visitProjectedRenderNodes(view, ngContentIndex, action, parentNode, nextSibling, target) {
var /** @type {?} */ compView = view;
while (compView && !isComponentView(compView)) {
compView = compView.parent;
}
var /** @type {?} */ hostView = ((compView)).parent;
var /** @type {?} */ hostElDef = viewParentEl(/** @type {?} */ ((compView)));
var /** @type {?} */ startIndex = ((hostElDef)).index + 1;
var /** @type {?} */ endIndex = ((hostElDef)).index + ((hostElDef)).childCount;
for (var /** @type {?} */ i = startIndex; i <= endIndex; i++) {
var /** @type {?} */ nodeDef = ((hostView)).def.nodes[i];
if (nodeDef.ngContentIndex === ngContentIndex) {
visitRenderNode(/** @type {?} */ ((hostView)), nodeDef, action, parentNode, nextSibling, target);
}
// jump to next sibling
i += nodeDef.childCount;
}
if (!((hostView)).parent) {
// a root view
var /** @type {?} */ projectedNodes = view.root.projectableNodes[ngContentIndex];
if (projectedNodes) {
for (var /** @type {?} */ i = 0; i < projectedNodes.length; i++) {
execRenderNodeAction(view, projectedNodes[i], action, parentNode, nextSibling, target);
}
}
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} action
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function visitRenderNode(view, nodeDef, action, parentNode, nextSibling, target) {
if (nodeDef.flags & 4 /* TypeNgContent */) {
visitProjectedRenderNodes(view, /** @type {?} */ ((nodeDef.ngContent)).index, action, parentNode, nextSibling, target);
}
else {
var /** @type {?} */ rn = renderNode(view, nodeDef);
if (action === 3 /* RemoveChild */ && (nodeDef.flags & 16777216 /* ComponentView */) &&
(nodeDef.bindingFlags & 48 /* CatSyntheticProperty */)) {
// Note: we might need to do both actions.
if (nodeDef.bindingFlags & (16 /* SyntheticProperty */)) {
execRenderNodeAction(view, rn, action, parentNode, nextSibling, target);
}
if (nodeDef.bindingFlags & (32 /* SyntheticHostProperty */)) {
var /** @type {?} */ compView = asElementData(view, nodeDef.index).componentView;
execRenderNodeAction(compView, rn, action, parentNode, nextSibling, target);
}
}
else {
execRenderNodeAction(view, rn, action, parentNode, nextSibling, target);
}
if (nodeDef.flags & 8388608 /* EmbeddedViews */) {
var /** @type {?} */ embeddedViews = ((asElementData(view, nodeDef.index).viewContainer))._embeddedViews;
for (var /** @type {?} */ k = 0; k < embeddedViews.length; k++) {
visitRootRenderNodes(embeddedViews[k], action, parentNode, nextSibling, target);
}
}
if (nodeDef.flags & 1 /* TypeElement */ && !((nodeDef.element)).name) {
visitSiblingRenderNodes(view, action, nodeDef.index + 1, nodeDef.index + nodeDef.childCount, parentNode, nextSibling, target);
}
}
}
/**
* @param {?} view
* @param {?} renderNode
* @param {?} action
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function execRenderNodeAction(view, renderNode, action, parentNode, nextSibling, target) {
var /** @type {?} */ renderer = view.renderer;
switch (action) {
case 1 /* AppendChild */:
renderer.appendChild(parentNode, renderNode);
break;
case 2 /* InsertBefore */:
renderer.insertBefore(parentNode, renderNode, nextSibling);
break;
case 3 /* RemoveChild */:
renderer.removeChild(parentNode, renderNode);
break;
case 0 /* Collect */:
((target)).push(renderNode);
break;
}
}
var NS_PREFIX_RE = /^:([^:]+):(.+)$/;
/**
* @param {?} name
* @return {?}
*/
function splitNamespace(name) {
if (name[0] === ':') {
var /** @type {?} */ match = ((name.match(NS_PREFIX_RE)));
return [match[1], match[2]];
}
return ['', name];
}
/**
* @param {?} bindings
* @return {?}
*/
function calcBindingFlags(bindings) {
var /** @type {?} */ flags = 0;
for (var /** @type {?} */ i = 0; i < bindings.length; i++) {
flags |= bindings[i].flags;
}
return flags;
}
/**
* @param {?} valueCount
* @param {?} constAndInterp
* @return {?}
*/
function interpolate(valueCount, constAndInterp) {
var /** @type {?} */ result = '';
for (var /** @type {?} */ i = 0; i < valueCount * 2; i = i + 2) {
result = result + constAndInterp[i] + _toStringWithNull(constAndInterp[i + 1]);
}
return result + constAndInterp[valueCount * 2];
}
/**
* @param {?} valueCount
* @param {?} c0
* @param {?} a1
* @param {?} c1
* @param {?=} a2
* @param {?=} c2
* @param {?=} a3
* @param {?=} c3
* @param {?=} a4
* @param {?=} c4
* @param {?=} a5
* @param {?=} c5
* @param {?=} a6
* @param {?=} c6
* @param {?=} a7
* @param {?=} c7
* @param {?=} a8
* @param {?=} c8
* @param {?=} a9
* @param {?=} c9
* @return {?}
*/
function inlineInterpolate(valueCount, c0, a1, c1, a2, c2, a3, c3, a4, c4, a5, c5, a6, c6, a7, c7, a8, c8, a9, c9) {
switch (valueCount) {
case 1:
return c0 + _toStringWithNull(a1) + c1;
case 2:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2;
case 3:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3;
case 4:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4;
case 5:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5;
case 6:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) + c6;
case 7:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
c6 + _toStringWithNull(a7) + c7;
case 8:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8;
case 9:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8 + _toStringWithNull(a9) + c9;
default:
throw new Error("Does not support more than 9 expressions");
}
}
/**
* @param {?} v
* @return {?}
*/
function _toStringWithNull(v) {
return v != null ? v.toString() : '';
}
var EMPTY_ARRAY = [];
var EMPTY_MAP = {};
/**
* @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
*/
/**
* @param {?} flags
* @param {?} matchedQueriesDsl
* @param {?} ngContentIndex
* @param {?} childCount
* @param {?=} handleEvent
* @param {?=} templateFactory
* @return {?}
*/
function anchorDef(flags, matchedQueriesDsl, ngContentIndex, childCount, handleEvent, templateFactory) {
flags |= 1 /* TypeElement */;
var _a = splitMatchedQueriesDsl(matchedQueriesDsl), matchedQueries = _a.matchedQueries, references = _a.references, matchedQueryIds = _a.matchedQueryIds;
var /** @type {?} */ template = templateFactory ? resolveViewDefinition(templateFactory) : null;
return {
// will bet set by the view definition
index: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
flags: flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0, matchedQueries: matchedQueries, matchedQueryIds: matchedQueryIds, references: references, ngContentIndex: ngContentIndex, childCount: childCount,
bindings: [],
bindingFlags: 0,
outputs: [],
element: {
ns: null,
name: null,
attrs: null, template: template,
componentProvider: null,
componentView: null,
componentRendererType: null,
publicProviders: null,
allProviders: null,
handleEvent: handleEvent || NOOP
},
provider: null,
text: null,
query: null,
ngContent: null
};
}
/**
* @param {?} flags
* @param {?} matchedQueriesDsl
* @param {?} ngContentIndex
* @param {?} childCount
* @param {?} namespaceAndName
* @param {?=} fixedAttrs
* @param {?=} bindings
* @param {?=} outputs
* @param {?=} handleEvent
* @param {?=} componentView
* @param {?=} componentRendererType
* @return {?}
*/
function elementDef(flags, matchedQueriesDsl, ngContentIndex, childCount, namespaceAndName, fixedAttrs, bindings, outputs, handleEvent, componentView, componentRendererType) {
if (fixedAttrs === void 0) { fixedAttrs = []; }
if (!handleEvent) {
handleEvent = NOOP;
}
var _a = splitMatchedQueriesDsl(matchedQueriesDsl), matchedQueries = _a.matchedQueries, references = _a.references, matchedQueryIds = _a.matchedQueryIds;
var /** @type {?} */ ns = ((null));
var /** @type {?} */ name = ((null));
if (namespaceAndName) {
_b = splitNamespace(namespaceAndName), ns = _b[0], name = _b[1];
}
bindings = bindings || [];
var /** @type {?} */ bindingDefs = new Array(bindings.length);
for (var /** @type {?} */ i = 0; i < bindings.length; i++) {
var _c = bindings[i], bindingFlags = _c[0], namespaceAndName_1 = _c[1], suffixOrSecurityContext = _c[2];
var _d = splitNamespace(namespaceAndName_1), ns_1 = _d[0], name_1 = _d[1];
var /** @type {?} */ securityContext = ((undefined));
var /** @type {?} */ suffix = ((undefined));
switch (bindingFlags & 15 /* Types */) {
case 4 /* TypeElementStyle */:
suffix = (suffixOrSecurityContext);
break;
case 1 /* TypeElementAttribute */:
case 8 /* TypeProperty */:
securityContext = (suffixOrSecurityContext);
break;
}
bindingDefs[i] =
{ flags: bindingFlags, ns: ns_1, name: name_1, nonMinifiedName: name_1, securityContext: securityContext, suffix: suffix };
}
outputs = outputs || [];
var /** @type {?} */ outputDefs = new Array(outputs.length);
for (var /** @type {?} */ i = 0; i < outputs.length; i++) {
var _e = outputs[i], target = _e[0], eventName = _e[1];
outputDefs[i] = {
type: 0 /* ElementOutput */,
target: /** @type {?} */ (target), eventName: eventName,
propName: null
};
}
fixedAttrs = fixedAttrs || [];
var /** @type {?} */ attrs = (fixedAttrs.map(function (_a) {
var namespaceAndName = _a[0], value = _a[1];
var _b = splitNamespace(namespaceAndName), ns = _b[0], name = _b[1];
return [ns, name, value];
}));
componentRendererType = resolveRendererType2(componentRendererType);
if (componentView) {
flags |= 16777216 /* ComponentView */;
}
flags |= 1 /* TypeElement */;
return {
// will bet set by the view definition
index: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
flags: flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0, matchedQueries: matchedQueries, matchedQueryIds: matchedQueryIds, references: references, ngContentIndex: ngContentIndex, childCount: childCount,
bindings: bindingDefs,
bindingFlags: calcBindingFlags(bindingDefs),
outputs: outputDefs,
element: {
ns: ns,
name: name,
attrs: attrs,
template: null,
// will bet set by the view definition
componentProvider: null,
componentView: componentView || null,
componentRendererType: componentRendererType,
publicProviders: null,
allProviders: null,
handleEvent: handleEvent || NOOP,
},
provider: null,
text: null,
query: null,
ngContent: null
};
var _b;
}
/**
* @param {?} view
* @param {?} renderHost
* @param {?} def
* @return {?}
*/
function createElement(view, renderHost, def) {
var /** @type {?} */ elDef = ((def.element));
var /** @type {?} */ rootSelectorOrNode = view.root.selectorOrNode;
var /** @type {?} */ renderer = view.renderer;
var /** @type {?} */ el;
if (view.parent || !rootSelectorOrNode) {
if (elDef.name) {
el = renderer.createElement(elDef.name, elDef.ns);
}
else {
el = renderer.createComment('');
}
var /** @type {?} */ parentEl = getParentRenderElement(view, renderHost, def);
if (parentEl) {
renderer.appendChild(parentEl, el);
}
}
else {
el = renderer.selectRootElement(rootSelectorOrNode);
}
if (elDef.attrs) {
for (var /** @type {?} */ i = 0; i < elDef.attrs.length; i++) {
var _a = elDef.attrs[i], ns = _a[0], name = _a[1], value = _a[2];
renderer.setAttribute(el, name, value, ns);
}
}
return el;
}
/**
* @param {?} view
* @param {?} compView
* @param {?} def
* @param {?} el
* @return {?}
*/
function listenToElementOutputs(view, compView, def, el) {
for (var /** @type {?} */ i = 0; i < def.outputs.length; i++) {
var /** @type {?} */ output = def.outputs[i];
var /** @type {?} */ handleEventClosure = renderEventHandlerClosure(view, def.index, elementEventFullName(output.target, output.eventName));
var /** @type {?} */ listenTarget = output.target;
var /** @type {?} */ listenerView = view;
if (output.target === 'component') {
listenTarget = null;
listenerView = compView;
}
var /** @type {?} */ disposable = (listenerView.renderer.listen(listenTarget || el, output.eventName, handleEventClosure)); /** @type {?} */
((view.disposables))[def.outputIndex + i] = disposable;
}
}
/**
* @param {?} view
* @param {?} index
* @param {?} eventName
* @return {?}
*/
function renderEventHandlerClosure(view, index, eventName) {
return function (event) {
try {
return dispatchEvent(view, index, eventName, event);
}
catch (e) {
// Attention: Don't rethrow, to keep in sync with directive events.
view.root.errorHandler.handleError(e);
}
};
}
/**
* @param {?} view
* @param {?} def
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkAndUpdateElementInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
var /** @type {?} */ bindLen = def.bindings.length;
var /** @type {?} */ changed = false;
if (bindLen > 0 && checkAndUpdateElementValue(view, def, 0, v0))
changed = true;
if (bindLen > 1 && checkAndUpdateElementValue(view, def, 1, v1))
changed = true;
if (bindLen > 2 && checkAndUpdateElementValue(view, def, 2, v2))
changed = true;
if (bindLen > 3 && checkAndUpdateElementValue(view, def, 3, v3))
changed = true;
if (bindLen > 4 && checkAndUpdateElementValue(view, def, 4, v4))
changed = true;
if (bindLen > 5 && checkAndUpdateElementValue(view, def, 5, v5))
changed = true;
if (bindLen > 6 && checkAndUpdateElementValue(view, def, 6, v6))
changed = true;
if (bindLen > 7 && checkAndUpdateElementValue(view, def, 7, v7))
changed = true;
if (bindLen > 8 && checkAndUpdateElementValue(view, def, 8, v8))
changed = true;
if (bindLen > 9 && checkAndUpdateElementValue(view, def, 9, v9))
changed = true;
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} values
* @return {?}
*/
function checkAndUpdateElementDynamic(view, def, values) {
var /** @type {?} */ changed = false;
for (var /** @type {?} */ i = 0; i < values.length; i++) {
if (checkAndUpdateElementValue(view, def, i, values[i]))
changed = true;
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function checkAndUpdateElementValue(view, def, bindingIdx, value) {
if (!checkAndUpdateBinding(view, def, bindingIdx, value)) {
return false;
}
var /** @type {?} */ binding = def.bindings[bindingIdx];
var /** @type {?} */ elData = asElementData(view, def.index);
var /** @type {?} */ renderNode$$1 = elData.renderElement;
var /** @type {?} */ name = ((binding.name));
switch (binding.flags & 15 /* Types */) {
case 1 /* TypeElementAttribute */:
setElementAttribute(view, binding, renderNode$$1, binding.ns, name, value);
break;
case 2 /* TypeElementClass */:
setElementClass(view, renderNode$$1, name, value);
break;
case 4 /* TypeElementStyle */:
setElementStyle(view, binding, renderNode$$1, name, value);
break;
case 8 /* TypeProperty */:
var /** @type {?} */ bindView = (def.flags & 16777216 /* ComponentView */ &&
binding.flags & 32 /* SyntheticHostProperty */) ?
elData.componentView :
view;
setElementProperty(bindView, binding, renderNode$$1, name, value);
break;
}
return true;
}
/**
* @param {?} view
* @param {?} binding
* @param {?} renderNode
* @param {?} ns
* @param {?} name
* @param {?} value
* @return {?}
*/
function setElementAttribute(view, binding, renderNode$$1, ns, name, value) {
var /** @type {?} */ securityContext = binding.securityContext;
var /** @type {?} */ renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value;
renderValue = renderValue != null ? renderValue.toString() : null;
var /** @type {?} */ renderer = view.renderer;
if (value != null) {
renderer.setAttribute(renderNode$$1, name, renderValue, ns);
}
else {
renderer.removeAttribute(renderNode$$1, name, ns);
}
}
/**
* @param {?} view
* @param {?} renderNode
* @param {?} name
* @param {?} value
* @return {?}
*/
function setElementClass(view, renderNode$$1, name, value) {
var /** @type {?} */ renderer = view.renderer;
if (value) {
renderer.addClass(renderNode$$1, name);
}
else {
renderer.removeClass(renderNode$$1, name);
}
}
/**
* @param {?} view
* @param {?} binding
* @param {?} renderNode
* @param {?} name
* @param {?} value
* @return {?}
*/
function setElementStyle(view, binding, renderNode$$1, name, value) {
var /** @type {?} */ renderValue = view.root.sanitizer.sanitize(SecurityContext.STYLE, /** @type {?} */ (value));
if (renderValue != null) {
renderValue = renderValue.toString();
var /** @type {?} */ unit = binding.suffix;
if (unit != null) {
renderValue = renderValue + unit;
}
}
else {
renderValue = null;
}
var /** @type {?} */ renderer = view.renderer;
if (renderValue != null) {
renderer.setStyle(renderNode$$1, name, renderValue);
}
else {
renderer.removeStyle(renderNode$$1, name);
}
}
/**
* @param {?} view
* @param {?} binding
* @param {?} renderNode
* @param {?} name
* @param {?} value
* @return {?}
*/
function setElementProperty(view, binding, renderNode$$1, name, value) {
var /** @type {?} */ securityContext = binding.securityContext;
var /** @type {?} */ renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value;
view.renderer.setProperty(renderNode$$1, name, renderValue);
}
/**
* @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
*/
/**
* @param {?} ngContentIndex
* @param {?} index
* @return {?}
*/
function ngContentDef(ngContentIndex, index) {
return {
// will bet set by the view definition
index: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
flags: 4 /* TypeNgContent */,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries: {},
matchedQueryIds: 0,
references: {}, ngContentIndex: ngContentIndex,
childCount: 0,
bindings: [],
bindingFlags: 0,
outputs: [],
element: null,
provider: null,
text: null,
query: null,
ngContent: { index: index }
};
}
/**
* @param {?} view
* @param {?} renderHost
* @param {?} def
* @return {?}
*/
function appendNgContent(view, renderHost, def) {
var /** @type {?} */ parentEl = getParentRenderElement(view, renderHost, def);
if (!parentEl) {
// Nothing to do if there is no parent element.
return;
}
var /** @type {?} */ ngContentIndex = ((def.ngContent)).index;
visitProjectedRenderNodes(view, ngContentIndex, 1 /* AppendChild */, parentEl, null, undefined);
}
/**
* @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
*/
/**
* @param {?} parentView
* @param {?} elementData
* @param {?} viewIndex
* @param {?} view
* @return {?}
*/
function attachEmbeddedView(parentView, elementData, viewIndex, view) {
var /** @type {?} */ embeddedViews = ((elementData.viewContainer))._embeddedViews;
if (viewIndex === null || viewIndex === undefined) {
viewIndex = embeddedViews.length;
}
view.viewContainerParent = parentView;
addToArray(embeddedViews, /** @type {?} */ ((viewIndex)), view);
var /** @type {?} */ dvcElementData = declaredViewContainer(view);
if (dvcElementData && dvcElementData !== elementData) {
var /** @type {?} */ projectedViews = dvcElementData.template._projectedViews;
if (!projectedViews) {
projectedViews = dvcElementData.template._projectedViews = [];
}
projectedViews.push(view);
}
Services.dirtyParentQueries(view);
var /** @type {?} */ prevView = ((viewIndex)) > 0 ? embeddedViews[((viewIndex)) - 1] : null;
renderAttachEmbeddedView(elementData, prevView, view);
}
/**
* @param {?} elementData
* @param {?=} viewIndex
* @return {?}
*/
function detachEmbeddedView(elementData, viewIndex) {
var /** @type {?} */ embeddedViews = ((elementData.viewContainer))._embeddedViews;
if (viewIndex == null || viewIndex >= embeddedViews.length) {
viewIndex = embeddedViews.length - 1;
}
if (viewIndex < 0) {
return null;
}
var /** @type {?} */ view = embeddedViews[viewIndex];
view.viewContainerParent = null;
removeFromArray(embeddedViews, viewIndex);
var /** @type {?} */ dvcElementData = declaredViewContainer(view);
if (dvcElementData && dvcElementData !== elementData) {
var /** @type {?} */ projectedViews = dvcElementData.template._projectedViews;
removeFromArray(projectedViews, projectedViews.indexOf(view));
}
Services.dirtyParentQueries(view);
renderDetachView(view);
return view;
}
/**
* @param {?} elementData
* @param {?} oldViewIndex
* @param {?} newViewIndex
* @return {?}
*/
function moveEmbeddedView(elementData, oldViewIndex, newViewIndex) {
var /** @type {?} */ embeddedViews = ((elementData.viewContainer))._embeddedViews;
var /** @type {?} */ view = embeddedViews[oldViewIndex];
removeFromArray(embeddedViews, oldViewIndex);
if (newViewIndex == null) {
newViewIndex = embeddedViews.length;
}
addToArray(embeddedViews, newViewIndex, view);
// Note: Don't need to change projectedViews as the order in there
// as always invalid...
Services.dirtyParentQueries(view);
renderDetachView(view);
var /** @type {?} */ prevView = newViewIndex > 0 ? embeddedViews[newViewIndex - 1] : null;
renderAttachEmbeddedView(elementData, prevView, view);
return view;
}
/**
* @param {?} elementData
* @param {?} prevView
* @param {?} view
* @return {?}
*/
function renderAttachEmbeddedView(elementData, prevView, view) {
var /** @type {?} */ prevRenderNode = prevView ? renderNode(prevView, /** @type {?} */ ((prevView.def.lastRenderRootNode))) :
elementData.renderElement;
var /** @type {?} */ parentNode = view.renderer.parentNode(prevRenderNode);
var /** @type {?} */ nextSibling = view.renderer.nextSibling(prevRenderNode);
// Note: We can't check if `nextSibling` is present, as on WebWorkers it will always be!
// However, browsers automatically do `appendChild` when there is no `nextSibling`.
visitRootRenderNodes(view, 2 /* InsertBefore */, parentNode, nextSibling, undefined);
}
/**
* @param {?} view
* @return {?}
*/
function renderDetachView(view) {
visitRootRenderNodes(view, 3 /* RemoveChild */, null, null, undefined);
}
/**
* @param {?} arr
* @param {?} index
* @param {?} value
* @return {?}
*/
function addToArray(arr, index, value) {
// perf: array.push is faster than array.splice!
if (index >= arr.length) {
arr.push(value);
}
else {
arr.splice(index, 0, value);
}
}
/**
* @param {?} arr
* @param {?} index
* @return {?}
*/
function removeFromArray(arr, index) {
// perf: array.pop is faster than array.splice!
if (index >= arr.length - 1) {
arr.pop();
}
else {
arr.splice(index, 1);
}
}
/**
* @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
*/
var EMPTY_CONTEXT = new Object();
/**
* @param {?} selector
* @param {?} componentType
* @param {?} viewDefFactory
* @param {?} inputs
* @param {?} outputs
* @param {?} ngContentSelectors
* @return {?}
*/
function createComponentFactory(selector, componentType, viewDefFactory, inputs, outputs, ngContentSelectors) {
return new ComponentFactory_(selector, componentType, viewDefFactory, inputs, outputs, ngContentSelectors);
}
/**
* @param {?} componentFactory
* @return {?}
*/
function getComponentViewDefinitionFactory(componentFactory) {
return ((componentFactory)).viewDefFactory;
}
var ComponentFactory_ = (function (_super) {
__extends(ComponentFactory_, _super);
/**
* @param {?} selector
* @param {?} componentType
* @param {?} viewDefFactory
* @param {?} _inputs
* @param {?} _outputs
* @param {?} ngContentSelectors
*/
function ComponentFactory_(selector, componentType, viewDefFactory, _inputs, _outputs, ngContentSelectors) {
var _this =
// Attention: this ctor is called as top level function.
// Putting any logic in here will destroy closure tree shaking!
_super.call(this) || this;
_this.selector = selector;
_this.componentType = componentType;
_this._inputs = _inputs;
_this._outputs = _outputs;
_this.ngContentSelectors = ngContentSelectors;
_this.viewDefFactory = viewDefFactory;
return _this;
}
Object.defineProperty(ComponentFactory_.prototype, "inputs", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ inputsArr = [];
var /** @type {?} */ inputs = ((this._inputs));
for (var /** @type {?} */ propName in inputs) {
var /** @type {?} */ templateName = inputs[propName];
inputsArr.push({ propName: propName, templateName: templateName });
}
return inputsArr;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ComponentFactory_.prototype, "outputs", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ outputsArr = [];
for (var /** @type {?} */ propName in this._outputs) {
var /** @type {?} */ templateName = this._outputs[propName];
outputsArr.push({ propName: propName, templateName: templateName });
}
return outputsArr;
},
enumerable: true,
configurable: true
});
/**
* Creates a new component.
* @param {?} injector
* @param {?=} projectableNodes
* @param {?=} rootSelectorOrNode
* @param {?=} ngModule
* @return {?}
*/
ComponentFactory_.prototype.create = function (injector, projectableNodes, rootSelectorOrNode, ngModule) {
if (!ngModule) {
throw new Error('ngModule should be provided');
}
var /** @type {?} */ viewDef = resolveViewDefinition(this.viewDefFactory);
var /** @type {?} */ componentNodeIndex = ((((viewDef.nodes[0].element)).componentProvider)).index;
var /** @type {?} */ view = Services.createRootView(injector, projectableNodes || [], rootSelectorOrNode, viewDef, ngModule, EMPTY_CONTEXT);
var /** @type {?} */ component = asProviderData(view, componentNodeIndex).instance;
if (rootSelectorOrNode) {
view.renderer.setAttribute(asElementData(view, 0).renderElement, 'ng-version', VERSION.full);
}
return new ComponentRef_(view, new ViewRef_(view), component);
};
return ComponentFactory_;
}(ComponentFactory));
var ComponentRef_ = (function (_super) {
__extends(ComponentRef_, _super);
/**
* @param {?} _view
* @param {?} _viewRef
* @param {?} _component
*/
function ComponentRef_(_view, _viewRef, _component) {
var _this = _super.call(this) || this;
_this._view = _view;
_this._viewRef = _viewRef;
_this._component = _component;
_this._elDef = _this._view.def.nodes[0];
return _this;
}
Object.defineProperty(ComponentRef_.prototype, "location", {
/**
* @return {?}
*/
get: function () {
return new ElementRef(asElementData(this._view, this._elDef.index).renderElement);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ComponentRef_.prototype, "injector", {
/**
* @return {?}
*/
get: function () { return new Injector_(this._view, this._elDef); },
enumerable: true,
configurable: true
});
Object.defineProperty(ComponentRef_.prototype, "instance", {
/**
* @return {?}
*/
get: function () { return this._component; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(ComponentRef_.prototype, "hostView", {
/**
* @return {?}
*/
get: function () { return this._viewRef; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(ComponentRef_.prototype, "changeDetectorRef", {
/**
* @return {?}
*/
get: function () { return this._viewRef; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(ComponentRef_.prototype, "componentType", {
/**
* @return {?}
*/
get: function () { return (this._component.constructor); },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
ComponentRef_.prototype.destroy = function () { this._viewRef.destroy(); };
/**
* @param {?} callback
* @return {?}
*/
ComponentRef_.prototype.onDestroy = function (callback) { this._viewRef.onDestroy(callback); };
return ComponentRef_;
}(ComponentRef));
/**
* @param {?} view
* @param {?} elDef
* @param {?} elData
* @return {?}
*/
function createViewContainerData(view, elDef, elData) {
return new ViewContainerRef_(view, elDef, elData);
}
var ViewContainerRef_ = (function () {
/**
* @param {?} _view
* @param {?} _elDef
* @param {?} _data
*/
function ViewContainerRef_(_view, _elDef, _data) {
this._view = _view;
this._elDef = _elDef;
this._data = _data;
/**
* \@internal
*/
this._embeddedViews = [];
}
Object.defineProperty(ViewContainerRef_.prototype, "element", {
/**
* @return {?}
*/
get: function () { return new ElementRef(this._data.renderElement); },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewContainerRef_.prototype, "injector", {
/**
* @return {?}
*/
get: function () { return new Injector_(this._view, this._elDef); },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewContainerRef_.prototype, "parentInjector", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ view = this._view;
var /** @type {?} */ elDef = this._elDef.parent;
while (!elDef && view) {
elDef = viewParentEl(view);
view = ((view.parent));
}
return view ? new Injector_(view, elDef) : new Injector_(this._view, null);
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
ViewContainerRef_.prototype.clear = function () {
var /** @type {?} */ len = this._embeddedViews.length;
for (var /** @type {?} */ i = len - 1; i >= 0; i--) {
var /** @type {?} */ view = ((detachEmbeddedView(this._data, i)));
Services.destroyView(view);
}
};
/**
* @param {?} index
* @return {?}
*/
ViewContainerRef_.prototype.get = function (index) {
var /** @type {?} */ view = this._embeddedViews[index];
if (view) {
var /** @type {?} */ ref = new ViewRef_(view);
ref.attachToViewContainerRef(this);
return ref;
}
return null;
};
Object.defineProperty(ViewContainerRef_.prototype, "length", {
/**
* @return {?}
*/
get: function () { return this._embeddedViews.length; },
enumerable: true,
configurable: true
});
;
/**
* @template C
* @param {?} templateRef
* @param {?=} context
* @param {?=} index
* @return {?}
*/
ViewContainerRef_.prototype.createEmbeddedView = function (templateRef, context, index) {
var /** @type {?} */ viewRef = templateRef.createEmbeddedView(context || ({}));
this.insert(viewRef, index);
return viewRef;
};
/**
* @template C
* @param {?} componentFactory
* @param {?=} index
* @param {?=} injector
* @param {?=} projectableNodes
* @param {?=} ngModuleRef
* @return {?}
*/
ViewContainerRef_.prototype.createComponent = function (componentFactory, index, injector, projectableNodes, ngModuleRef) {
var /** @type {?} */ contextInjector = injector || this.parentInjector;
if (!ngModuleRef && !(componentFactory instanceof ComponentFactoryBoundToModule)) {
ngModuleRef = contextInjector.get(NgModuleRef);
}
var /** @type {?} */ componentRef = componentFactory.create(contextInjector, projectableNodes, undefined, ngModuleRef);
this.insert(componentRef.hostView, index);
return componentRef;
};
/**
* @param {?} viewRef
* @param {?=} index
* @return {?}
*/
ViewContainerRef_.prototype.insert = function (viewRef, index) {
var /** @type {?} */ viewRef_ = (viewRef);
var /** @type {?} */ viewData = viewRef_._view;
attachEmbeddedView(this._view, this._data, index, viewData);
viewRef_.attachToViewContainerRef(this);
return viewRef;
};
/**
* @param {?} viewRef
* @param {?} currentIndex
* @return {?}
*/
ViewContainerRef_.prototype.move = function (viewRef, currentIndex) {
var /** @type {?} */ previousIndex = this._embeddedViews.indexOf(viewRef._view);
moveEmbeddedView(this._data, previousIndex, currentIndex);
return viewRef;
};
/**
* @param {?} viewRef
* @return {?}
*/
ViewContainerRef_.prototype.indexOf = function (viewRef) {
return this._embeddedViews.indexOf(((viewRef))._view);
};
/**
* @param {?=} index
* @return {?}
*/
ViewContainerRef_.prototype.remove = function (index) {
var /** @type {?} */ viewData = detachEmbeddedView(this._data, index);
if (viewData) {
Services.destroyView(viewData);
}
};
/**
* @param {?=} index
* @return {?}
*/
ViewContainerRef_.prototype.detach = function (index) {
var /** @type {?} */ view = detachEmbeddedView(this._data, index);
return view ? new ViewRef_(view) : null;
};
return ViewContainerRef_;
}());
/**
* @param {?} view
* @return {?}
*/
function createChangeDetectorRef(view) {
return new ViewRef_(view);
}
var ViewRef_ = (function () {
/**
* @param {?} _view
*/
function ViewRef_(_view) {
this._view = _view;
this._viewContainerRef = null;
this._appRef = null;
}
Object.defineProperty(ViewRef_.prototype, "rootNodes", {
/**
* @return {?}
*/
get: function () { return rootRenderNodes(this._view); },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewRef_.prototype, "context", {
/**
* @return {?}
*/
get: function () { return this._view.context; },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewRef_.prototype, "destroyed", {
/**
* @return {?}
*/
get: function () { return (this._view.state & 16 /* Destroyed */) !== 0; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
ViewRef_.prototype.markForCheck = function () { markParentViewsForCheck(this._view); };
/**
* @return {?}
*/
ViewRef_.prototype.detach = function () { this._view.state &= ~4 /* Attached */; };
/**
* @return {?}
*/
ViewRef_.prototype.detectChanges = function () { Services.checkAndUpdateView(this._view); };
/**
* @return {?}
*/
ViewRef_.prototype.checkNoChanges = function () { Services.checkNoChangesView(this._view); };
/**
* @return {?}
*/
ViewRef_.prototype.reattach = function () { this._view.state |= 4 /* Attached */; };
/**
* @param {?} callback
* @return {?}
*/
ViewRef_.prototype.onDestroy = function (callback) {
if (!this._view.disposables) {
this._view.disposables = [];
}
this._view.disposables.push(/** @type {?} */ (callback));
};
/**
* @return {?}
*/
ViewRef_.prototype.destroy = function () {
if (this._appRef) {
this._appRef.detachView(this);
}
else if (this._viewContainerRef) {
this._viewContainerRef.detach(this._viewContainerRef.indexOf(this));
}
Services.destroyView(this._view);
};
/**
* @return {?}
*/
ViewRef_.prototype.detachFromAppRef = function () {
this._appRef = null;
renderDetachView(this._view);
Services.dirtyParentQueries(this._view);
};
/**
* @param {?} appRef
* @return {?}
*/
ViewRef_.prototype.attachToAppRef = function (appRef) {
if (this._viewContainerRef) {
throw new Error('This view is already attached to a ViewContainer!');
}
this._appRef = appRef;
};
/**
* @param {?} vcRef
* @return {?}
*/
ViewRef_.prototype.attachToViewContainerRef = function (vcRef) {
if (this._appRef) {
throw new Error('This view is already attached directly to the ApplicationRef!');
}
this._viewContainerRef = vcRef;
};
return ViewRef_;
}());
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createTemplateData(view, def) {
return new TemplateRef_(view, def);
}
var TemplateRef_ = (function (_super) {
__extends(TemplateRef_, _super);
/**
* @param {?} _parentView
* @param {?} _def
*/
function TemplateRef_(_parentView, _def) {
var _this = _super.call(this) || this;
_this._parentView = _parentView;
_this._def = _def;
return _this;
}
/**
* @param {?} context
* @return {?}
*/
TemplateRef_.prototype.createEmbeddedView = function (context) {
return new ViewRef_(Services.createEmbeddedView(this._parentView, this._def, context));
};
Object.defineProperty(TemplateRef_.prototype, "elementRef", {
/**
* @return {?}
*/
get: function () {
return new ElementRef(asElementData(this._parentView, this._def.index).renderElement);
},
enumerable: true,
configurable: true
});
return TemplateRef_;
}(TemplateRef));
/**
* @param {?} view
* @param {?} elDef
* @return {?}
*/
function createInjector(view, elDef) {
return new Injector_(view, elDef);
}
var Injector_ = (function () {
/**
* @param {?} view
* @param {?} elDef
*/
function Injector_(view, elDef) {
this.view = view;
this.elDef = elDef;
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
Injector_.prototype.get = function (token, notFoundValue) {
if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; }
var /** @type {?} */ allowPrivateServices = this.elDef ? (this.elDef.flags & 16777216 /* ComponentView */) !== 0 : false;
return Services.resolveDep(this.view, this.elDef, allowPrivateServices, { flags: 0 /* None */, token: token, tokenKey: tokenKey(token) }, notFoundValue);
};
return Injector_;
}());
/**
* @param {?} view
* @param {?} index
* @return {?}
*/
function nodeValue(view, index) {
var /** @type {?} */ def = view.def.nodes[index];
if (def.flags & 1 /* TypeElement */) {
var /** @type {?} */ elData = asElementData(view, def.index);
return ((def.element)).template ? elData.template : elData.renderElement;
}
else if (def.flags & 2 /* TypeText */) {
return asTextData(view, def.index).renderText;
}
else if (def.flags & (10112 /* CatProvider */ | 8 /* TypePipe */)) {
return asProviderData(view, def.index).instance;
}
throw new Error("Illegal state: read nodeValue for node index " + index);
}
/**
* @param {?} view
* @return {?}
*/
function createRendererV1(view) {
return new RendererAdapter(view.renderer);
}
var RendererAdapter = (function () {
/**
* @param {?} delegate
*/
function RendererAdapter(delegate) {
this.delegate = delegate;
}
/**
* @param {?} selectorOrNode
* @return {?}
*/
RendererAdapter.prototype.selectRootElement = function (selectorOrNode) {
return this.delegate.selectRootElement(selectorOrNode);
};
/**
* @param {?} parent
* @param {?} namespaceAndName
* @return {?}
*/
RendererAdapter.prototype.createElement = function (parent, namespaceAndName) {
var _a = splitNamespace(namespaceAndName), ns = _a[0], name = _a[1];
var /** @type {?} */ el = this.delegate.createElement(name, ns);
if (parent) {
this.delegate.appendChild(parent, el);
}
return el;
};
/**
* @param {?} hostElement
* @return {?}
*/
RendererAdapter.prototype.createViewRoot = function (hostElement) { return hostElement; };
/**
* @param {?} parentElement
* @return {?}
*/
RendererAdapter.prototype.createTemplateAnchor = function (parentElement) {
var /** @type {?} */ comment = this.delegate.createComment('');
if (parentElement) {
this.delegate.appendChild(parentElement, comment);
}
return comment;
};
/**
* @param {?} parentElement
* @param {?} value
* @return {?}
*/
RendererAdapter.prototype.createText = function (parentElement, value) {
var /** @type {?} */ node = this.delegate.createText(value);
if (parentElement) {
this.delegate.appendChild(parentElement, node);
}
return node;
};
/**
* @param {?} parentElement
* @param {?} nodes
* @return {?}
*/
RendererAdapter.prototype.projectNodes = function (parentElement, nodes) {
for (var /** @type {?} */ i = 0; i < nodes.length; i++) {
this.delegate.appendChild(parentElement, nodes[i]);
}
};
/**
* @param {?} node
* @param {?} viewRootNodes
* @return {?}
*/
RendererAdapter.prototype.attachViewAfter = function (node, viewRootNodes) {
var /** @type {?} */ parentElement = this.delegate.parentNode(node);
var /** @type {?} */ nextSibling = this.delegate.nextSibling(node);
for (var /** @type {?} */ i = 0; i < viewRootNodes.length; i++) {
this.delegate.insertBefore(parentElement, viewRootNodes[i], nextSibling);
}
};
/**
* @param {?} viewRootNodes
* @return {?}
*/
RendererAdapter.prototype.detachView = function (viewRootNodes) {
for (var /** @type {?} */ i = 0; i < viewRootNodes.length; i++) {
var /** @type {?} */ node = viewRootNodes[i];
var /** @type {?} */ parentElement = this.delegate.parentNode(node);
this.delegate.removeChild(parentElement, node);
}
};
/**
* @param {?} hostElement
* @param {?} viewAllNodes
* @return {?}
*/
RendererAdapter.prototype.destroyView = function (hostElement, viewAllNodes) {
for (var /** @type {?} */ i = 0; i < viewAllNodes.length; i++) {
((this.delegate.destroyNode))(viewAllNodes[i]);
}
};
/**
* @param {?} renderElement
* @param {?} name
* @param {?} callback
* @return {?}
*/
RendererAdapter.prototype.listen = function (renderElement, name, callback) {
return this.delegate.listen(renderElement, name, /** @type {?} */ (callback));
};
/**
* @param {?} target
* @param {?} name
* @param {?} callback
* @return {?}
*/
RendererAdapter.prototype.listenGlobal = function (target, name, callback) {
return this.delegate.listen(target, name, /** @type {?} */ (callback));
};
/**
* @param {?} renderElement
* @param {?} propertyName
* @param {?} propertyValue
* @return {?}
*/
RendererAdapter.prototype.setElementProperty = function (renderElement, propertyName, propertyValue) {
this.delegate.setProperty(renderElement, propertyName, propertyValue);
};
/**
* @param {?} renderElement
* @param {?} namespaceAndName
* @param {?} attributeValue
* @return {?}
*/
RendererAdapter.prototype.setElementAttribute = function (renderElement, namespaceAndName, attributeValue) {
var _a = splitNamespace(namespaceAndName), ns = _a[0], name = _a[1];
if (attributeValue != null) {
this.delegate.setAttribute(renderElement, name, attributeValue, ns);
}
else {
this.delegate.removeAttribute(renderElement, name, ns);
}
};
/**
* @param {?} renderElement
* @param {?} propertyName
* @param {?} propertyValue
* @return {?}
*/
RendererAdapter.prototype.setBindingDebugInfo = function (renderElement, propertyName, propertyValue) { };
/**
* @param {?} renderElement
* @param {?} className
* @param {?} isAdd
* @return {?}
*/
RendererAdapter.prototype.setElementClass = function (renderElement, className, isAdd) {
if (isAdd) {
this.delegate.addClass(renderElement, className);
}
else {
this.delegate.removeClass(renderElement, className);
}
};
/**
* @param {?} renderElement
* @param {?} styleName
* @param {?} styleValue
* @return {?}
*/
RendererAdapter.prototype.setElementStyle = function (renderElement, styleName, styleValue) {
if (styleValue != null) {
this.delegate.setStyle(renderElement, styleName, styleValue);
}
else {
this.delegate.removeStyle(renderElement, styleName);
}
};
/**
* @param {?} renderElement
* @param {?} methodName
* @param {?} args
* @return {?}
*/
RendererAdapter.prototype.invokeElementMethod = function (renderElement, methodName, args) {
((renderElement))[methodName].apply(renderElement, args);
};
/**
* @param {?} renderNode
* @param {?} text
* @return {?}
*/
RendererAdapter.prototype.setText = function (renderNode$$1, text) { this.delegate.setValue(renderNode$$1, text); };
/**
* @return {?}
*/
RendererAdapter.prototype.animate = function () { throw new Error('Renderer.animate is no longer supported!'); };
return RendererAdapter;
}());
/**
* @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
*/
var RendererV1TokenKey = tokenKey(Renderer);
var Renderer2TokenKey = tokenKey(Renderer2);
var ElementRefTokenKey = tokenKey(ElementRef);
var ViewContainerRefTokenKey = tokenKey(ViewContainerRef);
var TemplateRefTokenKey = tokenKey(TemplateRef);
var ChangeDetectorRefTokenKey = tokenKey(ChangeDetectorRef);
var InjectorRefTokenKey = tokenKey(Injector);
var NOT_CREATED = new Object();
/**
* @param {?} flags
* @param {?} matchedQueries
* @param {?} childCount
* @param {?} ctor
* @param {?} deps
* @param {?=} props
* @param {?=} outputs
* @return {?}
*/
function directiveDef(flags, matchedQueries, childCount, ctor, deps, props, outputs) {
var /** @type {?} */ bindings = [];
if (props) {
for (var /** @type {?} */ prop in props) {
var _a = props[prop], bindingIndex = _a[0], nonMinifiedName = _a[1];
bindings[bindingIndex] = {
flags: 8 /* TypeProperty */,
name: prop, nonMinifiedName: nonMinifiedName,
ns: null,
securityContext: null,
suffix: null
};
}
}
var /** @type {?} */ outputDefs = [];
if (outputs) {
for (var /** @type {?} */ propName in outputs) {
outputDefs.push({ type: 1 /* DirectiveOutput */, propName: propName, target: null, eventName: outputs[propName] });
}
}
flags |= 8192 /* TypeDirective */;
return _def(flags, matchedQueries, childCount, ctor, ctor, deps, bindings, outputDefs);
}
/**
* @param {?} flags
* @param {?} ctor
* @param {?} deps
* @return {?}
*/
function pipeDef(flags, ctor, deps) {
flags |= 8 /* TypePipe */;
return _def(flags, null, 0, ctor, ctor, deps);
}
/**
* @param {?} flags
* @param {?} matchedQueries
* @param {?} token
* @param {?} value
* @param {?} deps
* @return {?}
*/
function providerDef(flags, matchedQueries, token, value, deps) {
return _def(flags, matchedQueries, 0, token, value, deps);
}
/**
* @param {?} flags
* @param {?} matchedQueriesDsl
* @param {?} childCount
* @param {?} token
* @param {?} value
* @param {?} deps
* @param {?=} bindings
* @param {?=} outputs
* @return {?}
*/
function _def(flags, matchedQueriesDsl, childCount, token, value, deps, bindings, outputs) {
var _a = splitMatchedQueriesDsl(matchedQueriesDsl), matchedQueries = _a.matchedQueries, references = _a.references, matchedQueryIds = _a.matchedQueryIds;
if (!outputs) {
outputs = [];
}
if (!bindings) {
bindings = [];
}
var /** @type {?} */ depDefs = deps.map(function (value) {
var /** @type {?} */ token;
var /** @type {?} */ flags;
if (Array.isArray(value)) {
flags = value[0], token = value[1];
}
else {
flags = 0 /* None */;
token = value;
}
return { flags: flags, token: token, tokenKey: tokenKey(token) };
});
return {
// will bet set by the view definition
index: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
flags: flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0, matchedQueries: matchedQueries, matchedQueryIds: matchedQueryIds, references: references,
ngContentIndex: -1, childCount: childCount, bindings: bindings,
bindingFlags: calcBindingFlags(bindings), outputs: outputs,
element: null,
provider: { token: token, tokenKey: tokenKey(token), value: value, deps: depDefs },
text: null,
query: null,
ngContent: null
};
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createProviderInstance(view, def) {
return def.flags & 2048 /* LazyProvider */ ? NOT_CREATED : _createProviderInstance(view, def);
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createPipeInstance(view, def) {
// deps are looked up from component.
var /** @type {?} */ compView = view;
while (compView.parent && !isComponentView(compView)) {
compView = compView.parent;
}
// pipes can see the private services of the component
var /** @type {?} */ allowPrivateServices = true;
// pipes are always eager and classes!
return createClass(/** @type {?} */ ((compView.parent)), /** @type {?} */ ((viewParentEl(compView))), allowPrivateServices, /** @type {?} */ ((def.provider)).value, /** @type {?} */ ((def.provider)).deps);
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createDirectiveInstance(view, def) {
// components can see other private services, other directives can't.
var /** @type {?} */ allowPrivateServices = (def.flags & 16384 /* Component */) > 0;
// directives are always eager and classes!
var /** @type {?} */ instance = createClass(view, /** @type {?} */ ((def.parent)), allowPrivateServices, /** @type {?} */ ((def.provider)).value, /** @type {?} */ ((def.provider)).deps);
if (def.outputs.length) {
for (var /** @type {?} */ i = 0; i < def.outputs.length; i++) {
var /** @type {?} */ output = def.outputs[i];
var /** @type {?} */ subscription = instance[((output.propName))].subscribe(eventHandlerClosure(view, /** @type {?} */ ((def.parent)).index, output.eventName)); /** @type {?} */
((view.disposables))[def.outputIndex + i] = subscription.unsubscribe.bind(subscription);
}
}
return instance;
}
/**
* @param {?} view
* @param {?} index
* @param {?} eventName
* @return {?}
*/
function eventHandlerClosure(view, index, eventName) {
return function (event) {
try {
return dispatchEvent(view, index, eventName, event);
}
catch (e) {
// Attention: Don't rethrow, as it would cancel Observable subscriptions!
view.root.errorHandler.handleError(e);
}
};
}
/**
* @param {?} view
* @param {?} def
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkAndUpdateDirectiveInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
var /** @type {?} */ providerData = asProviderData(view, def.index);
var /** @type {?} */ directive = providerData.instance;
var /** @type {?} */ changed = false;
var /** @type {?} */ changes = ((undefined));
var /** @type {?} */ bindLen = def.bindings.length;
if (bindLen > 0 && checkBinding(view, def, 0, v0)) {
changed = true;
changes = updateProp(view, providerData, def, 0, v0, changes);
}
if (bindLen > 1 && checkBinding(view, def, 1, v1)) {
changed = true;
changes = updateProp(view, providerData, def, 1, v1, changes);
}
if (bindLen > 2 && checkBinding(view, def, 2, v2)) {
changed = true;
changes = updateProp(view, providerData, def, 2, v2, changes);
}
if (bindLen > 3 && checkBinding(view, def, 3, v3)) {
changed = true;
changes = updateProp(view, providerData, def, 3, v3, changes);
}
if (bindLen > 4 && checkBinding(view, def, 4, v4)) {
changed = true;
changes = updateProp(view, providerData, def, 4, v4, changes);
}
if (bindLen > 5 && checkBinding(view, def, 5, v5)) {
changed = true;
changes = updateProp(view, providerData, def, 5, v5, changes);
}
if (bindLen > 6 && checkBinding(view, def, 6, v6)) {
changed = true;
changes = updateProp(view, providerData, def, 6, v6, changes);
}
if (bindLen > 7 && checkBinding(view, def, 7, v7)) {
changed = true;
changes = updateProp(view, providerData, def, 7, v7, changes);
}
if (bindLen > 8 && checkBinding(view, def, 8, v8)) {
changed = true;
changes = updateProp(view, providerData, def, 8, v8, changes);
}
if (bindLen > 9 && checkBinding(view, def, 9, v9)) {
changed = true;
changes = updateProp(view, providerData, def, 9, v9, changes);
}
if (changes) {
directive.ngOnChanges(changes);
}
if ((view.state & 2 /* FirstCheck */) && (def.flags & 32768 /* OnInit */)) {
directive.ngOnInit();
}
if (def.flags & 131072 /* DoCheck */) {
directive.ngDoCheck();
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} values
* @return {?}
*/
function checkAndUpdateDirectiveDynamic(view, def, values) {
var /** @type {?} */ providerData = asProviderData(view, def.index);
var /** @type {?} */ directive = providerData.instance;
var /** @type {?} */ changed = false;
var /** @type {?} */ changes = ((undefined));
for (var /** @type {?} */ i = 0; i < values.length; i++) {
if (checkBinding(view, def, i, values[i])) {
changed = true;
changes = updateProp(view, providerData, def, i, values[i], changes);
}
}
if (changes) {
directive.ngOnChanges(changes);
}
if ((view.state & 2 /* FirstCheck */) && (def.flags & 32768 /* OnInit */)) {
directive.ngOnInit();
}
if (def.flags & 131072 /* DoCheck */) {
directive.ngDoCheck();
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function _createProviderInstance(view, def) {
// private services can see other private services
var /** @type {?} */ allowPrivateServices = (def.flags & 4096 /* PrivateProvider */) > 0;
var /** @type {?} */ providerDef = def.provider;
var /** @type {?} */ injectable;
switch (def.flags & 100673535 /* Types */) {
case 256 /* TypeClassProvider */:
injectable = createClass(view, /** @type {?} */ ((def.parent)), allowPrivateServices, /** @type {?} */ ((providerDef)).value, /** @type {?} */ ((providerDef)).deps);
break;
case 512 /* TypeFactoryProvider */:
injectable = callFactory(view, /** @type {?} */ ((def.parent)), allowPrivateServices, /** @type {?} */ ((providerDef)).value, /** @type {?} */ ((providerDef)).deps);
break;
case 1024 /* TypeUseExistingProvider */:
injectable = resolveDep(view, /** @type {?} */ ((def.parent)), allowPrivateServices, /** @type {?} */ ((providerDef)).deps[0]);
break;
case 128 /* TypeValueProvider */:
injectable = ((providerDef)).value;
break;
}
return injectable;
}
/**
* @param {?} view
* @param {?} elDef
* @param {?} allowPrivateServices
* @param {?} ctor
* @param {?} deps
* @return {?}
*/
function createClass(view, elDef, allowPrivateServices, ctor, deps) {
var /** @type {?} */ len = deps.length;
var /** @type {?} */ injectable;
switch (len) {
case 0:
injectable = new ctor();
break;
case 1:
injectable = new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]));
break;
case 2:
injectable = new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]));
break;
case 3:
injectable = new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2]));
break;
default:
var /** @type {?} */ depValues = new Array(len);
for (var /** @type {?} */ i = 0; i < len; i++) {
depValues[i] = resolveDep(view, elDef, allowPrivateServices, deps[i]);
}
injectable = new (ctor.bind.apply(ctor, [void 0].concat(depValues)))();
}
return injectable;
}
/**
* @param {?} view
* @param {?} elDef
* @param {?} allowPrivateServices
* @param {?} factory
* @param {?} deps
* @return {?}
*/
function callFactory(view, elDef, allowPrivateServices, factory, deps) {
var /** @type {?} */ len = deps.length;
var /** @type {?} */ injectable;
switch (len) {
case 0:
injectable = factory();
break;
case 1:
injectable = factory(resolveDep(view, elDef, allowPrivateServices, deps[0]));
break;
case 2:
injectable = factory(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]));
break;
case 3:
injectable = factory(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2]));
break;
default:
var /** @type {?} */ depValues = Array(len);
for (var /** @type {?} */ i = 0; i < len; i++) {
depValues[i] = resolveDep(view, elDef, allowPrivateServices, deps[i]);
}
injectable = factory.apply(void 0, depValues);
}
return injectable;
}
// This default value is when checking the hierarchy for a token.
//
// It means both:
// - the token is not provided by the current injector,
// - only the element injectors should be checked (ie do not check module injectors
//
// mod1
// /
// el1 mod2
// \ /
// el2
//
// When requesting el2.injector.get(token), we should check in the following order and return the
// first found value:
// - el2.injector.get(token, default)
// - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module
// - mod2.injector.get(token, default)
var NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};
/**
* @param {?} view
* @param {?} elDef
* @param {?} allowPrivateServices
* @param {?} depDef
* @param {?=} notFoundValue
* @return {?}
*/
function resolveDep(view, elDef, allowPrivateServices, depDef, notFoundValue) {
if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; }
if (depDef.flags & 8 /* Value */) {
return depDef.token;
}
var /** @type {?} */ startView = view;
if (depDef.flags & 2 /* Optional */) {
notFoundValue = null;
}
var /** @type {?} */ tokenKey$$1 = depDef.tokenKey;
if (tokenKey$$1 === ChangeDetectorRefTokenKey) {
// directives on the same element as a component should be able to control the change detector
// of that component as well.
allowPrivateServices = !!(elDef && ((elDef.element)).componentView);
}
if (elDef && (depDef.flags & 1 /* SkipSelf */)) {
allowPrivateServices = false;
elDef = ((elDef.parent));
}
while (view) {
if (elDef) {
switch (tokenKey$$1) {
case RendererV1TokenKey: {
var /** @type {?} */ compView = findCompView(view, elDef, allowPrivateServices);
return createRendererV1(compView);
}
case Renderer2TokenKey: {
var /** @type {?} */ compView = findCompView(view, elDef, allowPrivateServices);
return compView.renderer;
}
case ElementRefTokenKey:
return new ElementRef(asElementData(view, elDef.index).renderElement);
case ViewContainerRefTokenKey:
return asElementData(view, elDef.index).viewContainer;
case TemplateRefTokenKey: {
if (((elDef.element)).template) {
return asElementData(view, elDef.index).template;
}
break;
}
case ChangeDetectorRefTokenKey: {
var /** @type {?} */ cdView = findCompView(view, elDef, allowPrivateServices);
return createChangeDetectorRef(cdView);
}
case InjectorRefTokenKey:
return createInjector(view, elDef);
default:
var /** @type {?} */ providerDef_1 = (((allowPrivateServices ? ((elDef.element)).allProviders : ((elDef.element)).publicProviders)))[tokenKey$$1];
if (providerDef_1) {
var /** @type {?} */ providerData = asProviderData(view, providerDef_1.index);
if (providerData.instance === NOT_CREATED) {
providerData.instance = _createProviderInstance(view, providerDef_1);
}
return providerData.instance;
}
}
}
allowPrivateServices = isComponentView(view);
elDef = ((viewParentEl(view)));
view = ((view.parent));
}
var /** @type {?} */ value = startView.root.injector.get(depDef.token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR);
if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
// Return the value from the root element injector when
// - it provides it
// (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
// - the module injector should not be checked
// (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
return value;
}
return startView.root.ngModule.injector.get(depDef.token, notFoundValue);
}
/**
* @param {?} view
* @param {?} elDef
* @param {?} allowPrivateServices
* @return {?}
*/
function findCompView(view, elDef, allowPrivateServices) {
var /** @type {?} */ compView;
if (allowPrivateServices) {
compView = asElementData(view, elDef.index).componentView;
}
else {
compView = view;
while (compView.parent && !isComponentView(compView)) {
compView = compView.parent;
}
}
return compView;
}
/**
* @param {?} view
* @param {?} providerData
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @param {?} changes
* @return {?}
*/
function updateProp(view, providerData, def, bindingIdx, value, changes) {
if (def.flags & 16384 /* Component */) {
var /** @type {?} */ compView = asElementData(view, /** @type {?} */ ((def.parent)).index).componentView;
if (compView.def.flags & 2 /* OnPush */) {
compView.state |= 8 /* ChecksEnabled */;
}
}
var /** @type {?} */ binding = def.bindings[bindingIdx];
var /** @type {?} */ propName = ((binding.name));
// Note: This is still safe with Closure Compiler as
// the user passed in the property name as an object has to `providerDef`,
// so Closure Compiler will have renamed the property correctly already.
providerData.instance[propName] = value;
if (def.flags & 262144 /* OnChanges */) {
changes = changes || {};
var /** @type {?} */ oldValue = view.oldValues[def.bindingIndex + bindingIdx];
if (oldValue instanceof WrappedValue) {
oldValue = oldValue.wrapped;
}
var /** @type {?} */ binding_1 = def.bindings[bindingIdx];
changes[((binding_1.nonMinifiedName))] =
new SimpleChange(oldValue, value, (view.state & 2 /* FirstCheck */) !== 0);
}
view.oldValues[def.bindingIndex + bindingIdx] = value;
return changes;
}
/**
* @param {?} view
* @param {?} lifecycles
* @return {?}
*/
function callLifecycleHooksChildrenFirst(view, lifecycles) {
if (!(view.def.nodeFlags & lifecycles)) {
return;
}
var /** @type {?} */ nodes = view.def.nodes;
for (var /** @type {?} */ i = 0; i < nodes.length; i++) {
var /** @type {?} */ nodeDef = nodes[i];
var /** @type {?} */ parent = nodeDef.parent;
if (!parent && nodeDef.flags & lifecycles) {
// matching root node (e.g. a pipe)
callProviderLifecycles(view, i, nodeDef.flags & lifecycles);
}
if ((nodeDef.childFlags & lifecycles) === 0) {
// no child matches one of the lifecycles
i += nodeDef.childCount;
}
while (parent && (parent.flags & 1 /* TypeElement */) &&
i === parent.index + parent.childCount) {
// last child of an element
if (parent.directChildFlags & lifecycles) {
callElementProvidersLifecycles(view, parent, lifecycles);
}
parent = parent.parent;
}
}
}
/**
* @param {?} view
* @param {?} elDef
* @param {?} lifecycles
* @return {?}
*/
function callElementProvidersLifecycles(view, elDef, lifecycles) {
for (var /** @type {?} */ i = elDef.index + 1; i <= elDef.index + elDef.childCount; i++) {
var /** @type {?} */ nodeDef = view.def.nodes[i];
if (nodeDef.flags & lifecycles) {
callProviderLifecycles(view, i, nodeDef.flags & lifecycles);
}
// only visit direct children
i += nodeDef.childCount;
}
}
/**
* @param {?} view
* @param {?} index
* @param {?} lifecycles
* @return {?}
*/
function callProviderLifecycles(view, index, lifecycles) {
var /** @type {?} */ provider = asProviderData(view, index).instance;
if (provider === NOT_CREATED) {
return;
}
Services.setCurrentNode(view, index);
if (lifecycles & 524288 /* AfterContentInit */) {
provider.ngAfterContentInit();
}
if (lifecycles & 1048576 /* AfterContentChecked */) {
provider.ngAfterContentChecked();
}
if (lifecycles & 2097152 /* AfterViewInit */) {
provider.ngAfterViewInit();
}
if (lifecycles & 4194304 /* AfterViewChecked */) {
provider.ngAfterViewChecked();
}
if (lifecycles & 65536 /* OnDestroy */) {
provider.ngOnDestroy();
}
}
/**
* @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
*/
/**
* @param {?} argCount
* @return {?}
*/
function purePipeDef(argCount) {
// argCount + 1 to include the pipe as first arg
return _pureExpressionDef(64 /* TypePurePipe */, new Array(argCount + 1));
}
/**
* @param {?} argCount
* @return {?}
*/
function pureArrayDef(argCount) {
return _pureExpressionDef(16 /* TypePureArray */, new Array(argCount));
}
/**
* @param {?} propertyNames
* @return {?}
*/
function pureObjectDef(propertyNames) {
return _pureExpressionDef(32 /* TypePureObject */, propertyNames);
}
/**
* @param {?} flags
* @param {?} propertyNames
* @return {?}
*/
function _pureExpressionDef(flags, propertyNames) {
var /** @type {?} */ bindings = new Array(propertyNames.length);
for (var /** @type {?} */ i = 0; i < propertyNames.length; i++) {
var /** @type {?} */ prop = propertyNames[i];
bindings[i] = {
flags: 8 /* TypeProperty */,
name: prop,
ns: null,
nonMinifiedName: prop,
securityContext: null,
suffix: null
};
}
return {
// will bet set by the view definition
index: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
flags: flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries: {},
matchedQueryIds: 0,
references: {},
ngContentIndex: -1,
childCount: 0, bindings: bindings,
bindingFlags: calcBindingFlags(bindings),
outputs: [],
element: null,
provider: null,
text: null,
query: null,
ngContent: null
};
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createPureExpression(view, def) {
return { value: undefined };
}
/**
* @param {?} view
* @param {?} def
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkAndUpdatePureExpressionInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
var /** @type {?} */ bindings = def.bindings;
var /** @type {?} */ changed = false;
var /** @type {?} */ bindLen = bindings.length;
if (bindLen > 0 && checkAndUpdateBinding(view, def, 0, v0))
changed = true;
if (bindLen > 1 && checkAndUpdateBinding(view, def, 1, v1))
changed = true;
if (bindLen > 2 && checkAndUpdateBinding(view, def, 2, v2))
changed = true;
if (bindLen > 3 && checkAndUpdateBinding(view, def, 3, v3))
changed = true;
if (bindLen > 4 && checkAndUpdateBinding(view, def, 4, v4))
changed = true;
if (bindLen > 5 && checkAndUpdateBinding(view, def, 5, v5))
changed = true;
if (bindLen > 6 && checkAndUpdateBinding(view, def, 6, v6))
changed = true;
if (bindLen > 7 && checkAndUpdateBinding(view, def, 7, v7))
changed = true;
if (bindLen > 8 && checkAndUpdateBinding(view, def, 8, v8))
changed = true;
if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9))
changed = true;
if (changed) {
var /** @type {?} */ data = asPureExpressionData(view, def.index);
var /** @type {?} */ value = void 0;
switch (def.flags & 100673535 /* Types */) {
case 16 /* TypePureArray */:
value = new Array(bindings.length);
if (bindLen > 0)
value[0] = v0;
if (bindLen > 1)
value[1] = v1;
if (bindLen > 2)
value[2] = v2;
if (bindLen > 3)
value[3] = v3;
if (bindLen > 4)
value[4] = v4;
if (bindLen > 5)
value[5] = v5;
if (bindLen > 6)
value[6] = v6;
if (bindLen > 7)
value[7] = v7;
if (bindLen > 8)
value[8] = v8;
if (bindLen > 9)
value[9] = v9;
break;
case 32 /* TypePureObject */:
value = {};
if (bindLen > 0)
value[((bindings[0].name))] = v0;
if (bindLen > 1)
value[((bindings[1].name))] = v1;
if (bindLen > 2)
value[((bindings[2].name))] = v2;
if (bindLen > 3)
value[((bindings[3].name))] = v3;
if (bindLen > 4)
value[((bindings[4].name))] = v4;
if (bindLen > 5)
value[((bindings[5].name))] = v5;
if (bindLen > 6)
value[((bindings[6].name))] = v6;
if (bindLen > 7)
value[((bindings[7].name))] = v7;
if (bindLen > 8)
value[((bindings[8].name))] = v8;
if (bindLen > 9)
value[((bindings[9].name))] = v9;
break;
case 64 /* TypePurePipe */:
var /** @type {?} */ pipe = v0;
switch (bindLen) {
case 1:
value = pipe.transform(v0);
break;
case 2:
value = pipe.transform(v1);
break;
case 3:
value = pipe.transform(v1, v2);
break;
case 4:
value = pipe.transform(v1, v2, v3);
break;
case 5:
value = pipe.transform(v1, v2, v3, v4);
break;
case 6:
value = pipe.transform(v1, v2, v3, v4, v5);
break;
case 7:
value = pipe.transform(v1, v2, v3, v4, v5, v6);
break;
case 8:
value = pipe.transform(v1, v2, v3, v4, v5, v6, v7);
break;
case 9:
value = pipe.transform(v1, v2, v3, v4, v5, v6, v7, v8);
break;
case 10:
value = pipe.transform(v1, v2, v3, v4, v5, v6, v7, v8, v9);
break;
}
break;
}
data.value = value;
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} values
* @return {?}
*/
function checkAndUpdatePureExpressionDynamic(view, def, values) {
var /** @type {?} */ bindings = def.bindings;
var /** @type {?} */ changed = false;
for (var /** @type {?} */ i = 0; i < values.length; i++) {
// Note: We need to loop over all values, so that
// the old values are updates as well!
if (checkAndUpdateBinding(view, def, i, values[i])) {
changed = true;
}
}
if (changed) {
var /** @type {?} */ data = asPureExpressionData(view, def.index);
var /** @type {?} */ value = void 0;
switch (def.flags & 100673535 /* Types */) {
case 16 /* TypePureArray */:
value = values;
break;
case 32 /* TypePureObject */:
value = {};
for (var /** @type {?} */ i = 0; i < values.length; i++) {
value[((bindings[i].name))] = values[i];
}
break;
case 64 /* TypePurePipe */:
var /** @type {?} */ pipe = values[0];
var /** @type {?} */ params = values.slice(1);
value = pipe.transform.apply(pipe, params);
break;
}
data.value = value;
}
return changed;
}
/**
* @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
*/
/**
* @param {?} flags
* @param {?} id
* @param {?} bindings
* @return {?}
*/
function queryDef(flags, id, bindings) {
var /** @type {?} */ bindingDefs = [];
for (var /** @type {?} */ propName in bindings) {
var /** @type {?} */ bindingType = bindings[propName];
bindingDefs.push({ propName: propName, bindingType: bindingType });
}
return {
// will bet set by the view definition
index: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
flags: flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
ngContentIndex: -1,
matchedQueries: {},
matchedQueryIds: 0,
references: {},
childCount: 0,
bindings: [],
bindingFlags: 0,
outputs: [],
element: null,
provider: null,
text: null,
query: { id: id, filterId: filterQueryId(id), bindings: bindingDefs },
ngContent: null
};
}
/**
* @return {?}
*/
function createQuery() {
return new QueryList();
}
/**
* @param {?} view
* @return {?}
*/
function dirtyParentQueries(view) {
var /** @type {?} */ queryIds = view.def.nodeMatchedQueries;
while (view.parent && isEmbeddedView(view)) {
var /** @type {?} */ tplDef = ((view.parentNodeDef));
view = view.parent;
// content queries
var /** @type {?} */ end = tplDef.index + tplDef.childCount;
for (var /** @type {?} */ i = 0; i <= end; i++) {
var /** @type {?} */ nodeDef = view.def.nodes[i];
if ((nodeDef.flags & 33554432 /* TypeContentQuery */) &&
(nodeDef.flags & 268435456 /* DynamicQuery */) &&
(((nodeDef.query)).filterId & queryIds) === ((nodeDef.query)).filterId) {
asQueryList(view, i).setDirty();
}
if ((nodeDef.flags & 1 /* TypeElement */ && i + nodeDef.childCount < tplDef.index) ||
!(nodeDef.childFlags & 33554432 /* TypeContentQuery */) ||
!(nodeDef.childFlags & 268435456 /* DynamicQuery */)) {
// skip elements that don't contain the template element or no query.
i += nodeDef.childCount;
}
}
}
// view queries
if (view.def.nodeFlags & 67108864 /* TypeViewQuery */) {
for (var /** @type {?} */ i = 0; i < view.def.nodes.length; i++) {
var /** @type {?} */ nodeDef = view.def.nodes[i];
if ((nodeDef.flags & 67108864 /* TypeViewQuery */) && (nodeDef.flags & 268435456 /* DynamicQuery */)) {
asQueryList(view, i).setDirty();
}
// only visit the root nodes
i += nodeDef.childCount;
}
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @return {?}
*/
function checkAndUpdateQuery(view, nodeDef) {
var /** @type {?} */ queryList = asQueryList(view, nodeDef.index);
if (!queryList.dirty) {
return;
}
var /** @type {?} */ directiveInstance;
var /** @type {?} */ newValues = ((undefined));
if (nodeDef.flags & 33554432 /* TypeContentQuery */) {
var /** @type {?} */ elementDef_1 = ((((nodeDef.parent)).parent));
newValues = calcQueryValues(view, elementDef_1.index, elementDef_1.index + elementDef_1.childCount, /** @type {?} */ ((nodeDef.query)), []);
directiveInstance = asProviderData(view, /** @type {?} */ ((nodeDef.parent)).index).instance;
}
else if (nodeDef.flags & 67108864 /* TypeViewQuery */) {
newValues = calcQueryValues(view, 0, view.def.nodes.length - 1, /** @type {?} */ ((nodeDef.query)), []);
directiveInstance = view.component;
}
queryList.reset(newValues);
var /** @type {?} */ bindings = ((nodeDef.query)).bindings;
var /** @type {?} */ notify = false;
for (var /** @type {?} */ i = 0; i < bindings.length; i++) {
var /** @type {?} */ binding = bindings[i];
var /** @type {?} */ boundValue = void 0;
switch (binding.bindingType) {
case 0 /* First */:
boundValue = queryList.first;
break;
case 1 /* All */:
boundValue = queryList;
notify = true;
break;
}
directiveInstance[binding.propName] = boundValue;
}
if (notify) {
queryList.notifyOnChanges();
}
}
/**
* @param {?} view
* @param {?} startIndex
* @param {?} endIndex
* @param {?} queryDef
* @param {?} values
* @return {?}
*/
function calcQueryValues(view, startIndex, endIndex, queryDef, values) {
for (var /** @type {?} */ i = startIndex; i <= endIndex; i++) {
var /** @type {?} */ nodeDef = view.def.nodes[i];
var /** @type {?} */ valueType = nodeDef.matchedQueries[queryDef.id];
if (valueType != null) {
values.push(getQueryValue(view, nodeDef, valueType));
}
if (nodeDef.flags & 1 /* TypeElement */ && ((nodeDef.element)).template &&
(((((nodeDef.element)).template)).nodeMatchedQueries & queryDef.filterId) ===
queryDef.filterId) {
// check embedded views that were attached at the place of their template.
var /** @type {?} */ elementData = asElementData(view, i);
if (nodeDef.flags & 8388608 /* EmbeddedViews */) {
var /** @type {?} */ embeddedViews = ((elementData.viewContainer))._embeddedViews;
for (var /** @type {?} */ k = 0; k < embeddedViews.length; k++) {
var /** @type {?} */ embeddedView = embeddedViews[k];
var /** @type {?} */ dvc = declaredViewContainer(embeddedView);
if (dvc && dvc === elementData) {
calcQueryValues(embeddedView, 0, embeddedView.def.nodes.length - 1, queryDef, values);
}
}
}
var /** @type {?} */ projectedViews = elementData.template._projectedViews;
if (projectedViews) {
for (var /** @type {?} */ k = 0; k < projectedViews.length; k++) {
var /** @type {?} */ projectedView = projectedViews[k];
calcQueryValues(projectedView, 0, projectedView.def.nodes.length - 1, queryDef, values);
}
}
}
if ((nodeDef.childMatchedQueries & queryDef.filterId) !== queryDef.filterId) {
// if no child matches the query, skip the children.
i += nodeDef.childCount;
}
}
return values;
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} queryValueType
* @return {?}
*/
function getQueryValue(view, nodeDef, queryValueType) {
if (queryValueType != null) {
// a match
var /** @type {?} */ value = void 0;
switch (queryValueType) {
case 1 /* RenderElement */:
value = asElementData(view, nodeDef.index).renderElement;
break;
case 0 /* ElementRef */:
value = new ElementRef(asElementData(view, nodeDef.index).renderElement);
break;
case 2 /* TemplateRef */:
value = asElementData(view, nodeDef.index).template;
break;
case 3 /* ViewContainerRef */:
value = asElementData(view, nodeDef.index).viewContainer;
break;
case 4 /* Provider */:
value = asProviderData(view, nodeDef.index).instance;
break;
}
return value;
}
}
/**
* @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
*/
/**
* @param {?} ngContentIndex
* @param {?} constants
* @return {?}
*/
function textDef(ngContentIndex, constants) {
var /** @type {?} */ bindings = new Array(constants.length - 1);
for (var /** @type {?} */ i = 1; i < constants.length; i++) {
bindings[i - 1] = {
flags: 8 /* TypeProperty */,
name: null,
ns: null,
nonMinifiedName: null,
securityContext: null,
suffix: constants[i]
};
}
var /** @type {?} */ flags = 2;
return {
// will bet set by the view definition
index: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
flags: flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries: {},
matchedQueryIds: 0,
references: {}, ngContentIndex: ngContentIndex,
childCount: 0, bindings: bindings,
bindingFlags: calcBindingFlags(bindings),
outputs: [],
element: null,
provider: null,
text: { prefix: constants[0] },
query: null,
ngContent: null
};
}
/**
* @param {?} view
* @param {?} renderHost
* @param {?} def
* @return {?}
*/
function createText(view, renderHost, def) {
var /** @type {?} */ renderNode$$1;
var /** @type {?} */ renderer = view.renderer;
renderNode$$1 = renderer.createText(/** @type {?} */ ((def.text)).prefix);
var /** @type {?} */ parentEl = getParentRenderElement(view, renderHost, def);
if (parentEl) {
renderer.appendChild(parentEl, renderNode$$1);
}
return { renderText: renderNode$$1 };
}
/**
* @param {?} view
* @param {?} def
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkAndUpdateTextInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
var /** @type {?} */ changed = false;
var /** @type {?} */ bindings = def.bindings;
var /** @type {?} */ bindLen = bindings.length;
if (bindLen > 0 && checkAndUpdateBinding(view, def, 0, v0))
changed = true;
if (bindLen > 1 && checkAndUpdateBinding(view, def, 1, v1))
changed = true;
if (bindLen > 2 && checkAndUpdateBinding(view, def, 2, v2))
changed = true;
if (bindLen > 3 && checkAndUpdateBinding(view, def, 3, v3))
changed = true;
if (bindLen > 4 && checkAndUpdateBinding(view, def, 4, v4))
changed = true;
if (bindLen > 5 && checkAndUpdateBinding(view, def, 5, v5))
changed = true;
if (bindLen > 6 && checkAndUpdateBinding(view, def, 6, v6))
changed = true;
if (bindLen > 7 && checkAndUpdateBinding(view, def, 7, v7))
changed = true;
if (bindLen > 8 && checkAndUpdateBinding(view, def, 8, v8))
changed = true;
if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9))
changed = true;
if (changed) {
var /** @type {?} */ value = ((def.text)).prefix;
if (bindLen > 0)
value += _addInterpolationPart(v0, bindings[0]);
if (bindLen > 1)
value += _addInterpolationPart(v1, bindings[1]);
if (bindLen > 2)
value += _addInterpolationPart(v2, bindings[2]);
if (bindLen > 3)
value += _addInterpolationPart(v3, bindings[3]);
if (bindLen > 4)
value += _addInterpolationPart(v4, bindings[4]);
if (bindLen > 5)
value += _addInterpolationPart(v5, bindings[5]);
if (bindLen > 6)
value += _addInterpolationPart(v6, bindings[6]);
if (bindLen > 7)
value += _addInterpolationPart(v7, bindings[7]);
if (bindLen > 8)
value += _addInterpolationPart(v8, bindings[8]);
if (bindLen > 9)
value += _addInterpolationPart(v9, bindings[9]);
var /** @type {?} */ renderNode$$1 = asTextData(view, def.index).renderText;
view.renderer.setValue(renderNode$$1, value);
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} values
* @return {?}
*/
function checkAndUpdateTextDynamic(view, def, values) {
var /** @type {?} */ bindings = def.bindings;
var /** @type {?} */ changed = false;
for (var /** @type {?} */ i = 0; i < values.length; i++) {
// Note: We need to loop over all values, so that
// the old values are updates as well!
if (checkAndUpdateBinding(view, def, i, values[i])) {
changed = true;
}
}
if (changed) {
var /** @type {?} */ value = '';
for (var /** @type {?} */ i = 0; i < values.length; i++) {
value = value + _addInterpolationPart(values[i], bindings[i]);
}
value = ((def.text)).prefix + value;
var /** @type {?} */ renderNode$$1 = asTextData(view, def.index).renderText;
view.renderer.setValue(renderNode$$1, value);
}
return changed;
}
/**
* @param {?} value
* @param {?} binding
* @return {?}
*/
function _addInterpolationPart(value, binding) {
var /** @type {?} */ valueStr = value != null ? value.toString() : '';
return valueStr + binding.suffix;
}
/**
* @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
*/
/**
* @param {?} flags
* @param {?} nodes
* @param {?=} updateDirectives
* @param {?=} updateRenderer
* @return {?}
*/
function viewDef(flags, nodes, updateDirectives, updateRenderer) {
// clone nodes and set auto calculated values
var /** @type {?} */ viewBindingCount = 0;
var /** @type {?} */ viewDisposableCount = 0;
var /** @type {?} */ viewNodeFlags = 0;
var /** @type {?} */ viewRootNodeFlags = 0;
var /** @type {?} */ viewMatchedQueries = 0;
var /** @type {?} */ currentParent = null;
var /** @type {?} */ currentElementHasPublicProviders = false;
var /** @type {?} */ currentElementHasPrivateProviders = false;
var /** @type {?} */ lastRenderRootNode = null;
for (var /** @type {?} */ i = 0; i < nodes.length; i++) {
while (currentParent && i > currentParent.index + currentParent.childCount) {
var /** @type {?} */ newParent = currentParent.parent;
if (newParent) {
newParent.childFlags |= ((currentParent.childFlags));
newParent.childMatchedQueries |= currentParent.childMatchedQueries;
}
currentParent = newParent;
}
var /** @type {?} */ node = nodes[i];
node.index = i;
node.parent = currentParent;
node.bindingIndex = viewBindingCount;
node.outputIndex = viewDisposableCount;
// renderParent needs to account for ng-container!
var /** @type {?} */ currentRenderParent = void 0;
if (currentParent && currentParent.flags & 1 /* TypeElement */ &&
!((currentParent.element)).name) {
currentRenderParent = currentParent.renderParent;
}
else {
currentRenderParent = currentParent;
}
node.renderParent = currentRenderParent;
if (node.element) {
var /** @type {?} */ elDef = node.element;
elDef.publicProviders =
currentParent ? ((currentParent.element)).publicProviders : Object.create(null);
elDef.allProviders = elDef.publicProviders;
// Note: We assume that all providers of an element are before any child element!
currentElementHasPublicProviders = false;
currentElementHasPrivateProviders = false;
}
validateNode(currentParent, node, nodes.length);
viewNodeFlags |= node.flags;
viewMatchedQueries |= node.matchedQueryIds;
if (node.element && node.element.template) {
viewMatchedQueries |= node.element.template.nodeMatchedQueries;
}
if (currentParent) {
currentParent.childFlags |= node.flags;
currentParent.directChildFlags |= node.flags;
currentParent.childMatchedQueries |= node.matchedQueryIds;
if (node.element && node.element.template) {
currentParent.childMatchedQueries |= node.element.template.nodeMatchedQueries;
}
}
else {
viewRootNodeFlags |= node.flags;
}
viewBindingCount += node.bindings.length;
viewDisposableCount += node.outputs.length;
if (!currentRenderParent && (node.flags & 3 /* CatRenderNode */)) {
lastRenderRootNode = node;
}
if (node.flags & 10112 /* CatProvider */) {
if (!currentElementHasPublicProviders) {
currentElementHasPublicProviders = true; /** @type {?} */
((((
// Use prototypical inheritance to not get O(n^2) complexity...
currentParent)).element)).publicProviders =
Object.create(/** @type {?} */ ((((currentParent)).element)).publicProviders); /** @type {?} */
((((currentParent)).element)).allProviders = ((((currentParent)).element)).publicProviders;
}
var /** @type {?} */ isPrivateService = (node.flags & 4096 /* PrivateProvider */) !== 0;
var /** @type {?} */ isComponent = (node.flags & 16384 /* Component */) !== 0;
if (!isPrivateService || isComponent) {
((((((currentParent)).element)).publicProviders))[((node.provider)).tokenKey] = node;
}
else {
if (!currentElementHasPrivateProviders) {
currentElementHasPrivateProviders = true; /** @type {?} */
((((
// Use protoyypical inheritance to not get O(n^2) complexity...
currentParent)).element)).allProviders =
Object.create(/** @type {?} */ ((((currentParent)).element)).publicProviders);
} /** @type {?} */
((((((currentParent)).element)).allProviders))[((node.provider)).tokenKey] = node;
}
if (isComponent) {
((((currentParent)).element)).componentProvider = node;
}
}
if (node.childCount) {
currentParent = node;
}
}
while (currentParent) {
var /** @type {?} */ newParent = currentParent.parent;
if (newParent) {
newParent.childFlags |= currentParent.childFlags;
newParent.childMatchedQueries |= currentParent.childMatchedQueries;
}
currentParent = newParent;
}
var /** @type {?} */ handleEvent = function (view, nodeIndex, eventName, event) { return ((((nodes[nodeIndex].element)).handleEvent))(view, eventName, event); };
return {
// Will be filled later...
factory: null,
nodeFlags: viewNodeFlags,
rootNodeFlags: viewRootNodeFlags,
nodeMatchedQueries: viewMatchedQueries, flags: flags,
nodes: nodes,
updateDirectives: updateDirectives || NOOP,
updateRenderer: updateRenderer || NOOP,
handleEvent: handleEvent || NOOP,
bindingCount: viewBindingCount,
outputCount: viewDisposableCount, lastRenderRootNode: lastRenderRootNode
};
}
/**
* @param {?} parent
* @param {?} node
* @param {?} nodeCount
* @return {?}
*/
function validateNode(parent, node, nodeCount) {
var /** @type {?} */ template = node.element && node.element.template;
if (template) {
if (!template.lastRenderRootNode) {
throw new Error("Illegal State: Embedded templates without nodes are not allowed!");
}
if (template.lastRenderRootNode &&
template.lastRenderRootNode.flags & 8388608 /* EmbeddedViews */) {
throw new Error("Illegal State: Last root node of a template can't have embedded views, at index " + node.index + "!");
}
}
if (node.flags & 10112 /* CatProvider */) {
var /** @type {?} */ parentFlags = parent ? parent.flags : 0;
if ((parentFlags & 1 /* TypeElement */) === 0) {
throw new Error("Illegal State: Provider/Directive nodes need to be children of elements or anchors, at index " + node.index + "!");
}
}
if (node.query) {
if (node.flags & 33554432 /* TypeContentQuery */ &&
(!parent || (parent.flags & 8192 /* TypeDirective */) === 0)) {
throw new Error("Illegal State: Content Query nodes need to be children of directives, at index " + node.index + "!");
}
if (node.flags & 67108864 /* TypeViewQuery */ && parent) {
throw new Error("Illegal State: View Query nodes have to be top level nodes, at index " + node.index + "!");
}
}
if (node.childCount) {
var /** @type {?} */ parentEnd = parent ? parent.index + parent.childCount : nodeCount - 1;
if (node.index <= parentEnd && node.index + node.childCount > parentEnd) {
throw new Error("Illegal State: childCount of node leads outside of parent, at index " + node.index + "!");
}
}
}
/**
* @param {?} parent
* @param {?} anchorDef
* @param {?=} context
* @return {?}
*/
function createEmbeddedView(parent, anchorDef$$1, context) {
// embedded views are seen as siblings to the anchor, so we need
// to get the parent of the anchor and use it as parentIndex.
var /** @type {?} */ view = createView(parent.root, parent.renderer, parent, anchorDef$$1, /** @type {?} */ ((((anchorDef$$1.element)).template)));
initView(view, parent.component, context);
createViewNodes(view);
return view;
}
/**
* @param {?} root
* @param {?} def
* @param {?=} context
* @return {?}
*/
function createRootView(root, def, context) {
var /** @type {?} */ view = createView(root, root.renderer, null, null, def);
initView(view, context, context);
createViewNodes(view);
return view;
}
/**
* @param {?} root
* @param {?} renderer
* @param {?} parent
* @param {?} parentNodeDef
* @param {?} def
* @return {?}
*/
function createView(root, renderer, parent, parentNodeDef, def) {
var /** @type {?} */ nodes = new Array(def.nodes.length);
var /** @type {?} */ disposables = def.outputCount ? new Array(def.outputCount) : null;
var /** @type {?} */ view = {
def: def,
parent: parent,
viewContainerParent: null, parentNodeDef: parentNodeDef,
context: null,
component: null, nodes: nodes,
state: 13 /* CatInit */, root: root, renderer: renderer,
oldValues: new Array(def.bindingCount), disposables: disposables
};
return view;
}
/**
* @param {?} view
* @param {?} component
* @param {?} context
* @return {?}
*/
function initView(view, component, context) {
view.component = component;
view.context = context;
}
/**
* @param {?} view
* @return {?}
*/
function createViewNodes(view) {
var /** @type {?} */ renderHost;
if (isComponentView(view)) {
var /** @type {?} */ hostDef = view.parentNodeDef;
renderHost = asElementData(/** @type {?} */ ((view.parent)), /** @type {?} */ ((((hostDef)).parent)).index).renderElement;
}
var /** @type {?} */ def = view.def;
var /** @type {?} */ nodes = view.nodes;
for (var /** @type {?} */ i = 0; i < def.nodes.length; i++) {
var /** @type {?} */ nodeDef = def.nodes[i];
Services.setCurrentNode(view, i);
var /** @type {?} */ nodeData = void 0;
switch (nodeDef.flags & 100673535 /* Types */) {
case 1 /* TypeElement */:
var /** @type {?} */ el = (createElement(view, renderHost, nodeDef));
var /** @type {?} */ componentView = ((undefined));
if (nodeDef.flags & 16777216 /* ComponentView */) {
var /** @type {?} */ compViewDef = resolveViewDefinition(/** @type {?} */ ((((nodeDef.element)).componentView)));
var /** @type {?} */ rendererType = ((nodeDef.element)).componentRendererType;
var /** @type {?} */ compRenderer = void 0;
if (!rendererType) {
compRenderer = view.root.renderer;
}
else {
compRenderer = view.root.rendererFactory.createRenderer(el, rendererType);
}
componentView = createView(view.root, compRenderer, view, /** @type {?} */ ((nodeDef.element)).componentProvider, compViewDef);
}
listenToElementOutputs(view, componentView, nodeDef, el);
nodeData = ({
renderElement: el,
componentView: componentView,
viewContainer: null,
template: /** @type {?} */ ((nodeDef.element)).template ? createTemplateData(view, nodeDef) : undefined
});
if (nodeDef.flags & 8388608 /* EmbeddedViews */) {
nodeData.viewContainer = createViewContainerData(view, nodeDef, nodeData);
}
break;
case 2 /* TypeText */:
nodeData = (createText(view, renderHost, nodeDef));
break;
case 256 /* TypeClassProvider */:
case 512 /* TypeFactoryProvider */:
case 1024 /* TypeUseExistingProvider */:
case 128 /* TypeValueProvider */: {
var /** @type {?} */ instance = createProviderInstance(view, nodeDef);
nodeData = ({ instance: instance });
break;
}
case 8 /* TypePipe */: {
var /** @type {?} */ instance = createPipeInstance(view, nodeDef);
nodeData = ({ instance: instance });
break;
}
case 8192 /* TypeDirective */: {
var /** @type {?} */ instance = createDirectiveInstance(view, nodeDef);
nodeData = ({ instance: instance });
if (nodeDef.flags & 16384 /* Component */) {
var /** @type {?} */ compView = asElementData(view, /** @type {?} */ ((nodeDef.parent)).index).componentView;
initView(compView, instance, instance);
}
break;
}
case 16 /* TypePureArray */:
case 32 /* TypePureObject */:
case 64 /* TypePurePipe */:
nodeData = (createPureExpression(view, nodeDef));
break;
case 33554432 /* TypeContentQuery */:
case 67108864 /* TypeViewQuery */:
nodeData = (createQuery());
break;
case 4 /* TypeNgContent */:
appendNgContent(view, renderHost, nodeDef);
// no runtime data needed for NgContent...
nodeData = undefined;
break;
}
nodes[i] = nodeData;
}
// Create the ViewData.nodes of component views after we created everything else,
// so that e.g. ng-content works
execComponentViewsAction(view, ViewAction.CreateViewNodes);
// fill static content and view queries
execQueriesAction(view, 33554432 /* TypeContentQuery */ | 67108864 /* TypeViewQuery */, 134217728 /* StaticQuery */, 0 /* CheckAndUpdate */);
}
/**
* @param {?} view
* @return {?}
*/
function checkNoChangesView(view) {
Services.updateDirectives(view, 1 /* CheckNoChanges */);
execEmbeddedViewsAction(view, ViewAction.CheckNoChanges);
Services.updateRenderer(view, 1 /* CheckNoChanges */);
execComponentViewsAction(view, ViewAction.CheckNoChanges);
// Note: We don't check queries for changes as we didn't do this in v2.x.
// TODO(tbosch): investigate if we can enable the check again in v5.x with a nicer error message.
}
/**
* @param {?} view
* @return {?}
*/
function checkAndUpdateView(view) {
if (view.state & 1 /* BeforeFirstCheck */) {
view.state &= ~1 /* BeforeFirstCheck */;
view.state |= 2 /* FirstCheck */;
}
else {
view.state &= ~2 /* FirstCheck */;
}
Services.updateDirectives(view, 0 /* CheckAndUpdate */);
execEmbeddedViewsAction(view, ViewAction.CheckAndUpdate);
execQueriesAction(view, 33554432 /* TypeContentQuery */, 268435456 /* DynamicQuery */, 0 /* CheckAndUpdate */);
callLifecycleHooksChildrenFirst(view, 1048576 /* AfterContentChecked */ |
(view.state & 2 /* FirstCheck */ ? 524288 /* AfterContentInit */ : 0));
Services.updateRenderer(view, 0 /* CheckAndUpdate */);
execComponentViewsAction(view, ViewAction.CheckAndUpdate);
execQueriesAction(view, 67108864 /* TypeViewQuery */, 268435456 /* DynamicQuery */, 0 /* CheckAndUpdate */);
callLifecycleHooksChildrenFirst(view, 4194304 /* AfterViewChecked */ |
(view.state & 2 /* FirstCheck */ ? 2097152 /* AfterViewInit */ : 0));
if (view.def.flags & 2 /* OnPush */) {
view.state &= ~8 /* ChecksEnabled */;
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} argStyle
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function checkAndUpdateNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
if (argStyle === 0 /* Inline */) {
return checkAndUpdateNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
}
else {
return checkAndUpdateNodeDynamic(view, nodeDef, v0);
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function checkAndUpdateNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
var /** @type {?} */ changed = false;
switch (nodeDef.flags & 100673535 /* Types */) {
case 1 /* TypeElement */:
changed = checkAndUpdateElementInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
break;
case 2 /* TypeText */:
changed = checkAndUpdateTextInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
break;
case 8192 /* TypeDirective */:
changed =
checkAndUpdateDirectiveInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
break;
case 16 /* TypePureArray */:
case 32 /* TypePureObject */:
case 64 /* TypePurePipe */:
changed =
checkAndUpdatePureExpressionInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
break;
}
return changed;
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} values
* @return {?}
*/
function checkAndUpdateNodeDynamic(view, nodeDef, values) {
var /** @type {?} */ changed = false;
switch (nodeDef.flags & 100673535 /* Types */) {
case 1 /* TypeElement */:
changed = checkAndUpdateElementDynamic(view, nodeDef, values);
break;
case 2 /* TypeText */:
changed = checkAndUpdateTextDynamic(view, nodeDef, values);
break;
case 8192 /* TypeDirective */:
changed = checkAndUpdateDirectiveDynamic(view, nodeDef, values);
break;
case 16 /* TypePureArray */:
case 32 /* TypePureObject */:
case 64 /* TypePurePipe */:
changed = checkAndUpdatePureExpressionDynamic(view, nodeDef, values);
break;
}
if (changed) {
// Update oldValues after all bindings have been updated,
// as a setter for a property might update other properties.
var /** @type {?} */ bindLen = nodeDef.bindings.length;
var /** @type {?} */ bindingStart = nodeDef.bindingIndex;
var /** @type {?} */ oldValues = view.oldValues;
for (var /** @type {?} */ i = 0; i < bindLen; i++) {
oldValues[bindingStart + i] = values[i];
}
}
return changed;
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} argStyle
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function checkNoChangesNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
if (argStyle === 0 /* Inline */) {
checkNoChangesNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
}
else {
checkNoChangesNodeDynamic(view, nodeDef, v0);
}
// Returning false is ok here as we would have thrown in case of a change.
return false;
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkNoChangesNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
var /** @type {?} */ bindLen = nodeDef.bindings.length;
if (bindLen > 0)
checkBindingNoChanges(view, nodeDef, 0, v0);
if (bindLen > 1)
checkBindingNoChanges(view, nodeDef, 1, v1);
if (bindLen > 2)
checkBindingNoChanges(view, nodeDef, 2, v2);
if (bindLen > 3)
checkBindingNoChanges(view, nodeDef, 3, v3);
if (bindLen > 4)
checkBindingNoChanges(view, nodeDef, 4, v4);
if (bindLen > 5)
checkBindingNoChanges(view, nodeDef, 5, v5);
if (bindLen > 6)
checkBindingNoChanges(view, nodeDef, 6, v6);
if (bindLen > 7)
checkBindingNoChanges(view, nodeDef, 7, v7);
if (bindLen > 8)
checkBindingNoChanges(view, nodeDef, 8, v8);
if (bindLen > 9)
checkBindingNoChanges(view, nodeDef, 9, v9);
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} values
* @return {?}
*/
function checkNoChangesNodeDynamic(view, nodeDef, values) {
for (var /** @type {?} */ i = 0; i < values.length; i++) {
checkBindingNoChanges(view, nodeDef, i, values[i]);
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @return {?}
*/
function checkNoChangesQuery(view, nodeDef) {
var /** @type {?} */ queryList = asQueryList(view, nodeDef.index);
if (queryList.dirty) {
throw expressionChangedAfterItHasBeenCheckedError(Services.createDebugContext(view, nodeDef.index), "Query " + ((nodeDef.query)).id + " not dirty", "Query " + ((nodeDef.query)).id + " dirty", (view.state & 1 /* BeforeFirstCheck */) !== 0);
}
}
/**
* @param {?} view
* @return {?}
*/
function destroyView(view) {
if (view.state & 16 /* Destroyed */) {
return;
}
execEmbeddedViewsAction(view, ViewAction.Destroy);
execComponentViewsAction(view, ViewAction.Destroy);
callLifecycleHooksChildrenFirst(view, 65536 /* OnDestroy */);
if (view.disposables) {
for (var /** @type {?} */ i = 0; i < view.disposables.length; i++) {
view.disposables[i]();
}
}
if (view.renderer.destroyNode) {
destroyViewNodes(view);
}
if (isComponentView(view)) {
view.renderer.destroy();
}
view.state |= 16 /* Destroyed */;
}
/**
* @param {?} view
* @return {?}
*/
function destroyViewNodes(view) {
var /** @type {?} */ len = view.def.nodes.length;
for (var /** @type {?} */ i = 0; i < len; i++) {
var /** @type {?} */ def = view.def.nodes[i];
if (def.flags & 1 /* TypeElement */) {
((view.renderer.destroyNode))(asElementData(view, i).renderElement);
}
else if (def.flags & 2 /* TypeText */) {
((view.renderer.destroyNode))(asTextData(view, i).renderText);
}
}
}
var ViewAction = {};
ViewAction.CreateViewNodes = 0;
ViewAction.CheckNoChanges = 1;
ViewAction.CheckAndUpdate = 2;
ViewAction.Destroy = 3;
ViewAction[ViewAction.CreateViewNodes] = "CreateViewNodes";
ViewAction[ViewAction.CheckNoChanges] = "CheckNoChanges";
ViewAction[ViewAction.CheckAndUpdate] = "CheckAndUpdate";
ViewAction[ViewAction.Destroy] = "Destroy";
/**
* @param {?} view
* @param {?} action
* @return {?}
*/
function execComponentViewsAction(view, action) {
var /** @type {?} */ def = view.def;
if (!(def.nodeFlags & 16777216 /* ComponentView */)) {
return;
}
for (var /** @type {?} */ i = 0; i < def.nodes.length; i++) {
var /** @type {?} */ nodeDef = def.nodes[i];
if (nodeDef.flags & 16777216 /* ComponentView */) {
// a leaf
callViewAction(asElementData(view, i).componentView, action);
}
else if ((nodeDef.childFlags & 16777216 /* ComponentView */) === 0) {
// a parent with leafs
// no child is a component,
// then skip the children
i += nodeDef.childCount;
}
}
}
/**
* @param {?} view
* @param {?} action
* @return {?}
*/
function execEmbeddedViewsAction(view, action) {
var /** @type {?} */ def = view.def;
if (!(def.nodeFlags & 8388608 /* EmbeddedViews */)) {
return;
}
for (var /** @type {?} */ i = 0; i < def.nodes.length; i++) {
var /** @type {?} */ nodeDef = def.nodes[i];
if (nodeDef.flags & 8388608 /* EmbeddedViews */) {
// a leaf
var /** @type {?} */ embeddedViews = ((asElementData(view, i).viewContainer))._embeddedViews;
for (var /** @type {?} */ k = 0; k < embeddedViews.length; k++) {
callViewAction(embeddedViews[k], action);
}
}
else if ((nodeDef.childFlags & 8388608 /* EmbeddedViews */) === 0) {
// a parent with leafs
// no child is a component,
// then skip the children
i += nodeDef.childCount;
}
}
}
/**
* @param {?} view
* @param {?} action
* @return {?}
*/
function callViewAction(view, action) {
var /** @type {?} */ viewState = view.state;
switch (action) {
case ViewAction.CheckNoChanges:
if ((viewState & 12 /* CatDetectChanges */) === 12 /* CatDetectChanges */ &&
(viewState & 16 /* Destroyed */) === 0) {
checkNoChangesView(view);
}
break;
case ViewAction.CheckAndUpdate:
if ((viewState & 12 /* CatDetectChanges */) === 12 /* CatDetectChanges */ &&
(viewState & 16 /* Destroyed */) === 0) {
checkAndUpdateView(view);
}
break;
case ViewAction.Destroy:
destroyView(view);
break;
case ViewAction.CreateViewNodes:
createViewNodes(view);
break;
}
}
/**
* @param {?} view
* @param {?} queryFlags
* @param {?} staticDynamicQueryFlag
* @param {?} checkType
* @return {?}
*/
function execQueriesAction(view, queryFlags, staticDynamicQueryFlag, checkType) {
if (!(view.def.nodeFlags & queryFlags) || !(view.def.nodeFlags & staticDynamicQueryFlag)) {
return;
}
var /** @type {?} */ nodeCount = view.def.nodes.length;
for (var /** @type {?} */ i = 0; i < nodeCount; i++) {
var /** @type {?} */ nodeDef = view.def.nodes[i];
if ((nodeDef.flags & queryFlags) && (nodeDef.flags & staticDynamicQueryFlag)) {
Services.setCurrentNode(view, nodeDef.index);
switch (checkType) {
case 0 /* CheckAndUpdate */:
checkAndUpdateQuery(view, nodeDef);
break;
case 1 /* CheckNoChanges */:
checkNoChangesQuery(view, nodeDef);
break;
}
}
if (!(nodeDef.childFlags & queryFlags) || !(nodeDef.childFlags & staticDynamicQueryFlag)) {
// no child has a matching query
// then skip the children
i += nodeDef.childCount;
}
}
}
/**
* @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
*/
var initialized = false;
/**
* @return {?}
*/
function initServicesIfNeeded() {
if (initialized) {
return;
}
initialized = true;
var /** @type {?} */ services = isDevMode() ? createDebugServices() : createProdServices();
Services.setCurrentNode = services.setCurrentNode;
Services.createRootView = services.createRootView;
Services.createEmbeddedView = services.createEmbeddedView;
Services.checkAndUpdateView = services.checkAndUpdateView;
Services.checkNoChangesView = services.checkNoChangesView;
Services.destroyView = services.destroyView;
Services.resolveDep = resolveDep;
Services.createDebugContext = services.createDebugContext;
Services.handleEvent = services.handleEvent;
Services.updateDirectives = services.updateDirectives;
Services.updateRenderer = services.updateRenderer;
Services.dirtyParentQueries = dirtyParentQueries;
}
/**
* @return {?}
*/
function createProdServices() {
return {
setCurrentNode: function () { },
createRootView: createProdRootView,
createEmbeddedView: createEmbeddedView,
checkAndUpdateView: checkAndUpdateView,
checkNoChangesView: checkNoChangesView,
destroyView: destroyView,
createDebugContext: function (view, nodeIndex) { return new DebugContext_(view, nodeIndex); },
handleEvent: function (view, nodeIndex, eventName, event) { return view.def.handleEvent(view, nodeIndex, eventName, event); },
updateDirectives: function (view, checkType) { return view.def.updateDirectives(checkType === 0 /* CheckAndUpdate */ ? prodCheckAndUpdateNode :
prodCheckNoChangesNode, view); },
updateRenderer: function (view, checkType) { return view.def.updateRenderer(checkType === 0 /* CheckAndUpdate */ ? prodCheckAndUpdateNode :
prodCheckNoChangesNode, view); },
};
}
/**
* @return {?}
*/
function createDebugServices() {
return {
setCurrentNode: debugSetCurrentNode,
createRootView: debugCreateRootView,
createEmbeddedView: debugCreateEmbeddedView,
checkAndUpdateView: debugCheckAndUpdateView,
checkNoChangesView: debugCheckNoChangesView,
destroyView: debugDestroyView,
createDebugContext: function (view, nodeIndex) { return new DebugContext_(view, nodeIndex); },
handleEvent: debugHandleEvent,
updateDirectives: debugUpdateDirectives,
updateRenderer: debugUpdateRenderer
};
}
/**
* @param {?} elInjector
* @param {?} projectableNodes
* @param {?} rootSelectorOrNode
* @param {?} def
* @param {?} ngModule
* @param {?=} context
* @return {?}
*/
function createProdRootView(elInjector, projectableNodes, rootSelectorOrNode, def, ngModule, context) {
var /** @type {?} */ rendererFactory = ngModule.injector.get(RendererFactory2);
return createRootView(createRootData(elInjector, ngModule, rendererFactory, projectableNodes, rootSelectorOrNode), def, context);
}
/**
* @param {?} elInjector
* @param {?} projectableNodes
* @param {?} rootSelectorOrNode
* @param {?} def
* @param {?} ngModule
* @param {?=} context
* @return {?}
*/
function debugCreateRootView(elInjector, projectableNodes, rootSelectorOrNode, def, ngModule, context) {
var /** @type {?} */ rendererFactory = ngModule.injector.get(RendererFactory2);
var /** @type {?} */ root = createRootData(elInjector, ngModule, new DebugRendererFactory2(rendererFactory), projectableNodes, rootSelectorOrNode);
return callWithDebugContext(DebugAction.create, createRootView, null, [root, def, context]);
}
/**
* @param {?} elInjector
* @param {?} ngModule
* @param {?} rendererFactory
* @param {?} projectableNodes
* @param {?} rootSelectorOrNode
* @return {?}
*/
function createRootData(elInjector, ngModule, rendererFactory, projectableNodes, rootSelectorOrNode) {
var /** @type {?} */ sanitizer = ngModule.injector.get(Sanitizer);
var /** @type {?} */ errorHandler = ngModule.injector.get(ErrorHandler);
var /** @type {?} */ renderer = rendererFactory.createRenderer(null, null);
return {
ngModule: ngModule,
injector: elInjector, projectableNodes: projectableNodes,
selectorOrNode: rootSelectorOrNode, sanitizer: sanitizer, rendererFactory: rendererFactory, renderer: renderer, errorHandler: errorHandler
};
}
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} argStyle
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function prodCheckAndUpdateNode(view, nodeIndex, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
var /** @type {?} */ nodeDef = view.def.nodes[nodeIndex];
checkAndUpdateNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
return (nodeDef.flags & 112 /* CatPureExpression */) ?
asPureExpressionData(view, nodeIndex).value :
undefined;
}
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} argStyle
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function prodCheckNoChangesNode(view, nodeIndex, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
var /** @type {?} */ nodeDef = view.def.nodes[nodeIndex];
checkNoChangesNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
return (nodeDef.flags & 112 /* CatPureExpression */) ?
asPureExpressionData(view, nodeIndex).value :
undefined;
}
/**
* @param {?} parent
* @param {?} anchorDef
* @param {?=} context
* @return {?}
*/
function debugCreateEmbeddedView(parent, anchorDef, context) {
return callWithDebugContext(DebugAction.create, createEmbeddedView, null, [parent, anchorDef, context]);
}
/**
* @param {?} view
* @return {?}
*/
function debugCheckAndUpdateView(view) {
return callWithDebugContext(DebugAction.detectChanges, checkAndUpdateView, null, [view]);
}
/**
* @param {?} view
* @return {?}
*/
function debugCheckNoChangesView(view) {
return callWithDebugContext(DebugAction.checkNoChanges, checkNoChangesView, null, [view]);
}
/**
* @param {?} view
* @return {?}
*/
function debugDestroyView(view) {
return callWithDebugContext(DebugAction.destroy, destroyView, null, [view]);
}
var DebugAction = {};
DebugAction.create = 0;
DebugAction.detectChanges = 1;
DebugAction.checkNoChanges = 2;
DebugAction.destroy = 3;
DebugAction.handleEvent = 4;
DebugAction[DebugAction.create] = "create";
DebugAction[DebugAction.detectChanges] = "detectChanges";
DebugAction[DebugAction.checkNoChanges] = "checkNoChanges";
DebugAction[DebugAction.destroy] = "destroy";
DebugAction[DebugAction.handleEvent] = "handleEvent";
var _currentAction;
var _currentView;
var _currentNodeIndex;
/**
* @param {?} view
* @param {?} nodeIndex
* @return {?}
*/
function debugSetCurrentNode(view, nodeIndex) {
_currentView = view;
_currentNodeIndex = nodeIndex;
}
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} eventName
* @param {?} event
* @return {?}
*/
function debugHandleEvent(view, nodeIndex, eventName, event) {
debugSetCurrentNode(view, nodeIndex);
return callWithDebugContext(DebugAction.handleEvent, view.def.handleEvent, null, [view, nodeIndex, eventName, event]);
}
/**
* @param {?} view
* @param {?} checkType
* @return {?}
*/
function debugUpdateDirectives(view, checkType) {
if (view.state & 16 /* Destroyed */) {
throw viewDestroyedError(DebugAction[_currentAction]);
}
debugSetCurrentNode(view, nextDirectiveWithBinding(view, 0));
return view.def.updateDirectives(debugCheckDirectivesFn, view);
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} argStyle
* @param {...?} values
* @return {?}
*/
function debugCheckDirectivesFn(view, nodeIndex, argStyle) {
var values = [];
for (var _i = 3; _i < arguments.length; _i++) {
values[_i - 3] = arguments[_i];
}
var /** @type {?} */ nodeDef = view.def.nodes[nodeIndex];
if (checkType === 0 /* CheckAndUpdate */) {
debugCheckAndUpdateNode(view, nodeDef, argStyle, values);
}
else {
debugCheckNoChangesNode(view, nodeDef, argStyle, values);
}
if (nodeDef.flags & 8192 /* TypeDirective */) {
debugSetCurrentNode(view, nextDirectiveWithBinding(view, nodeIndex));
}
return (nodeDef.flags & 112 /* CatPureExpression */) ?
asPureExpressionData(view, nodeDef.index).value :
undefined;
}
}
/**
* @param {?} view
* @param {?} checkType
* @return {?}
*/
function debugUpdateRenderer(view, checkType) {
if (view.state & 16 /* Destroyed */) {
throw viewDestroyedError(DebugAction[_currentAction]);
}
debugSetCurrentNode(view, nextRenderNodeWithBinding(view, 0));
return view.def.updateRenderer(debugCheckRenderNodeFn, view);
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} argStyle
* @param {...?} values
* @return {?}
*/
function debugCheckRenderNodeFn(view, nodeIndex, argStyle) {
var values = [];
for (var _i = 3; _i < arguments.length; _i++) {
values[_i - 3] = arguments[_i];
}
var /** @type {?} */ nodeDef = view.def.nodes[nodeIndex];
if (checkType === 0 /* CheckAndUpdate */) {
debugCheckAndUpdateNode(view, nodeDef, argStyle, values);
}
else {
debugCheckNoChangesNode(view, nodeDef, argStyle, values);
}
if (nodeDef.flags & 3 /* CatRenderNode */) {
debugSetCurrentNode(view, nextRenderNodeWithBinding(view, nodeIndex));
}
return (nodeDef.flags & 112 /* CatPureExpression */) ?
asPureExpressionData(view, nodeDef.index).value :
undefined;
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} argStyle
* @param {?} givenValues
* @return {?}
*/
function debugCheckAndUpdateNode(view, nodeDef, argStyle, givenValues) {
var /** @type {?} */ changed = ((checkAndUpdateNode)).apply(void 0, [view, nodeDef, argStyle].concat(givenValues));
if (changed) {
var /** @type {?} */ values = argStyle === 1 /* Dynamic */ ? givenValues[0] : givenValues;
if (nodeDef.flags & 8192 /* TypeDirective */) {
var /** @type {?} */ bindingValues = {};
for (var /** @type {?} */ i = 0; i < nodeDef.bindings.length; i++) {
var /** @type {?} */ binding = nodeDef.bindings[i];
var /** @type {?} */ value = values[i];
if (binding.flags & 8 /* TypeProperty */) {
bindingValues[normalizeDebugBindingName(/** @type {?} */ ((binding.nonMinifiedName)))] =
normalizeDebugBindingValue(value);
}
}
var /** @type {?} */ elDef = ((nodeDef.parent));
var /** @type {?} */ el = asElementData(view, elDef.index).renderElement;
if (!((elDef.element)).name) {
// a comment.
view.renderer.setValue(el, "bindings=" + JSON.stringify(bindingValues, null, 2));
}
else {
// a regular element.
for (var /** @type {?} */ attr in bindingValues) {
var /** @type {?} */ value = bindingValues[attr];
if (value != null) {
view.renderer.setAttribute(el, attr, value);
}
else {
view.renderer.removeAttribute(el, attr);
}
}
}
}
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} argStyle
* @param {?} values
* @return {?}
*/
function debugCheckNoChangesNode(view, nodeDef, argStyle, values) {
((checkNoChangesNode)).apply(void 0, [view, nodeDef, argStyle].concat(values));
}
/**
* @param {?} name
* @return {?}
*/
function normalizeDebugBindingName(name) {
// Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
return "ng-reflect-" + name;
}
var CAMEL_CASE_REGEXP = /([A-Z])/g;
/**
* @param {?} input
* @return {?}
*/
function camelCaseToDashCase(input) {
return input.replace(CAMEL_CASE_REGEXP, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
return '-' + m[1].toLowerCase();
});
}
/**
* @param {?} value
* @return {?}
*/
function normalizeDebugBindingValue(value) {
try {
// Limit the size of the value as otherwise the DOM just gets polluted.
return value != null ? value.toString().slice(0, 30) : value;
}
catch (e) {
return '[ERROR] Exception while trying to serialize the value';
}
}
/**
* @param {?} view
* @param {?} nodeIndex
* @return {?}
*/
function nextDirectiveWithBinding(view, nodeIndex) {
for (var /** @type {?} */ i = nodeIndex; i < view.def.nodes.length; i++) {
var /** @type {?} */ nodeDef = view.def.nodes[i];
if (nodeDef.flags & 8192 /* TypeDirective */ && nodeDef.bindings && nodeDef.bindings.length) {
return i;
}
}
return null;
}
/**
* @param {?} view
* @param {?} nodeIndex
* @return {?}
*/
function nextRenderNodeWithBinding(view, nodeIndex) {
for (var /** @type {?} */ i = nodeIndex; i < view.def.nodes.length; i++) {
var /** @type {?} */ nodeDef = view.def.nodes[i];
if ((nodeDef.flags & 3 /* CatRenderNode */) && nodeDef.bindings && nodeDef.bindings.length) {
return i;
}
}
return null;
}
var DebugContext_ = (function () {
/**
* @param {?} view
* @param {?} nodeIndex
*/
function DebugContext_(view, nodeIndex) {
this.view = view;
this.nodeIndex = nodeIndex;
if (nodeIndex == null) {
this.nodeIndex = nodeIndex = 0;
}
this.nodeDef = view.def.nodes[nodeIndex];
var elDef = this.nodeDef;
var elView = view;
while (elDef && (elDef.flags & 1 /* TypeElement */) === 0) {
elDef = elDef.parent;
}
if (!elDef) {
while (!elDef && elView) {
elDef = viewParentEl(elView);
elView = elView.parent;
}
}
this.elDef = elDef;
this.elView = elView;
}
Object.defineProperty(DebugContext_.prototype, "elOrCompView", {
/**
* @return {?}
*/
get: function () {
// Has to be done lazily as we use the DebugContext also during creation of elements...
return asElementData(this.elView, this.elDef.index).componentView || this.view;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DebugContext_.prototype, "injector", {
/**
* @return {?}
*/
get: function () { return createInjector(this.elView, this.elDef); },
enumerable: true,
configurable: true
});
Object.defineProperty(DebugContext_.prototype, "component", {
/**
* @return {?}
*/
get: function () { return this.elOrCompView.component; },
enumerable: true,
configurable: true
});
Object.defineProperty(DebugContext_.prototype, "context", {
/**
* @return {?}
*/
get: function () { return this.elOrCompView.context; },
enumerable: true,
configurable: true
});
Object.defineProperty(DebugContext_.prototype, "providerTokens", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ tokens = [];
if (this.elDef) {
for (var /** @type {?} */ i = this.elDef.index + 1; i <= this.elDef.index + this.elDef.childCount; i++) {
var /** @type {?} */ childDef = this.elView.def.nodes[i];
if (childDef.flags & 10112 /* CatProvider */) {
tokens.push(/** @type {?} */ ((childDef.provider)).token);
}
i += childDef.childCount;
}
}
return tokens;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DebugContext_.prototype, "references", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ references = {};
if (this.elDef) {
collectReferences(this.elView, this.elDef, references);
for (var /** @type {?} */ i = this.elDef.index + 1; i <= this.elDef.index + this.elDef.childCount; i++) {
var /** @type {?} */ childDef = this.elView.def.nodes[i];
if (childDef.flags & 10112 /* CatProvider */) {
collectReferences(this.elView, childDef, references);
}
i += childDef.childCount;
}
}
return references;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DebugContext_.prototype, "componentRenderElement", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ elData = findHostElement(this.elOrCompView);
return elData ? elData.renderElement : undefined;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DebugContext_.prototype, "renderNode", {
/**
* @return {?}
*/
get: function () {
return this.nodeDef.flags & 2 /* TypeText */ ? renderNode(this.view, this.nodeDef) :
renderNode(this.elView, this.elDef);
},
enumerable: true,
configurable: true
});
/**
* @param {?} console
* @param {...?} values
* @return {?}
*/
DebugContext_.prototype.logError = function (console) {
var values = [];
for (var _i = 1; _i < arguments.length; _i++) {
values[_i - 1] = arguments[_i];
}
var /** @type {?} */ logViewDef;
var /** @type {?} */ logNodeIndex;
if (this.nodeDef.flags & 2 /* TypeText */) {
logViewDef = this.view.def;
logNodeIndex = this.nodeDef.index;
}
else {
logViewDef = this.elView.def;
logNodeIndex = this.elDef.index;
}
// Note: we only generate a log function for text and element nodes
// to make the generated code as small as possible.
var /** @type {?} */ renderNodeIndex = getRenderNodeIndex(logViewDef, logNodeIndex);
var /** @type {?} */ currRenderNodeIndex = -1;
var /** @type {?} */ nodeLogger = function () {
currRenderNodeIndex++;
if (currRenderNodeIndex === renderNodeIndex) {
return (_a = console.error).bind.apply(_a, [console].concat(values));
}
else {
return NOOP;
}
var _a;
}; /** @type {?} */
((logViewDef.factory))(nodeLogger);
if (currRenderNodeIndex < renderNodeIndex) {
console.error('Illegal state: the ViewDefinitionFactory did not call the logger!');
console.error.apply(console, values);
}
};
return DebugContext_;
}());
/**
* @param {?} viewDef
* @param {?} nodeIndex
* @return {?}
*/
function getRenderNodeIndex(viewDef$$1, nodeIndex) {
var /** @type {?} */ renderNodeIndex = -1;
for (var /** @type {?} */ i = 0; i <= nodeIndex; i++) {
var /** @type {?} */ nodeDef = viewDef$$1.nodes[i];
if (nodeDef.flags & 3 /* CatRenderNode */) {
renderNodeIndex++;
}
}
return renderNodeIndex;
}
/**
* @param {?} view
* @return {?}
*/
function findHostElement(view) {
while (view && !isComponentView(view)) {
view = ((view.parent));
}
if (view.parent) {
return asElementData(view.parent, /** @type {?} */ ((viewParentEl(view))).index);
}
return null;
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} references
* @return {?}
*/
function collectReferences(view, nodeDef, references) {
for (var /** @type {?} */ refName in nodeDef.references) {
references[refName] = getQueryValue(view, nodeDef, nodeDef.references[refName]);
}
}
/**
* @param {?} action
* @param {?} fn
* @param {?} self
* @param {?} args
* @return {?}
*/
function callWithDebugContext(action, fn, self, args) {
var /** @type {?} */ oldAction = _currentAction;
var /** @type {?} */ oldView = _currentView;
var /** @type {?} */ oldNodeIndex = _currentNodeIndex;
try {
_currentAction = action;
var /** @type {?} */ result = fn.apply(self, args);
_currentView = oldView;
_currentNodeIndex = oldNodeIndex;
_currentAction = oldAction;
return result;
}
catch (e) {
if (isViewDebugError(e) || !_currentView) {
throw e;
}
throw viewWrappedDebugError(e, /** @type {?} */ ((getCurrentDebugContext())));
}
}
/**
* @return {?}
*/
function getCurrentDebugContext() {
return _currentView ? new DebugContext_(_currentView, _currentNodeIndex) : null;
}
var DebugRendererFactory2 = (function () {
/**
* @param {?} delegate
*/
function DebugRendererFactory2(delegate) {
this.delegate = delegate;
}
/**
* @param {?} element
* @param {?} renderData
* @return {?}
*/
DebugRendererFactory2.prototype.createRenderer = function (element, renderData) {
return new DebugRenderer2(this.delegate.createRenderer(element, renderData));
};
return DebugRendererFactory2;
}());
var DebugRenderer2 = (function () {
/**
* @param {?} delegate
*/
function DebugRenderer2(delegate) {
this.delegate = delegate;
}
Object.defineProperty(DebugRenderer2.prototype, "data", {
/**
* @return {?}
*/
get: function () { return this.delegate.data; },
enumerable: true,
configurable: true
});
/**
* @param {?} node
* @return {?}
*/
DebugRenderer2.prototype.destroyNode = function (node) {
removeDebugNodeFromIndex(/** @type {?} */ ((getDebugNode(node))));
if (this.delegate.destroyNode) {
this.delegate.destroyNode(node);
}
};
/**
* @return {?}
*/
DebugRenderer2.prototype.destroy = function () { this.delegate.destroy(); };
/**
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
DebugRenderer2.prototype.createElement = function (name, namespace) {
var /** @type {?} */ el = this.delegate.createElement(name, namespace);
var /** @type {?} */ debugCtx = getCurrentDebugContext();
if (debugCtx) {
var /** @type {?} */ debugEl = new DebugElement(el, null, debugCtx);
debugEl.name = name;
indexDebugNode(debugEl);
}
return el;
};
/**
* @param {?} value
* @return {?}
*/
DebugRenderer2.prototype.createComment = function (value) {
var /** @type {?} */ comment = this.delegate.createComment(value);
var /** @type {?} */ debugCtx = getCurrentDebugContext();
if (debugCtx) {
indexDebugNode(new DebugNode(comment, null, debugCtx));
}
return comment;
};
/**
* @param {?} value
* @return {?}
*/
DebugRenderer2.prototype.createText = function (value) {
var /** @type {?} */ text = this.delegate.createText(value);
var /** @type {?} */ debugCtx = getCurrentDebugContext();
if (debugCtx) {
indexDebugNode(new DebugNode(text, null, debugCtx));
}
return text;
};
/**
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
DebugRenderer2.prototype.appendChild = function (parent, newChild) {
var /** @type {?} */ debugEl = getDebugNode(parent);
var /** @type {?} */ debugChildEl = getDebugNode(newChild);
if (debugEl && debugChildEl && debugEl instanceof DebugElement) {
debugEl.addChild(debugChildEl);
}
this.delegate.appendChild(parent, newChild);
};
/**
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
DebugRenderer2.prototype.insertBefore = function (parent, newChild, refChild) {
var /** @type {?} */ debugEl = getDebugNode(parent);
var /** @type {?} */ debugChildEl = getDebugNode(newChild);
var /** @type {?} */ debugRefEl = ((getDebugNode(refChild)));
if (debugEl && debugChildEl && debugEl instanceof DebugElement) {
debugEl.insertBefore(debugRefEl, debugChildEl);
}
this.delegate.insertBefore(parent, newChild, refChild);
};
/**
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
DebugRenderer2.prototype.removeChild = function (parent, oldChild) {
var /** @type {?} */ debugEl = getDebugNode(parent);
var /** @type {?} */ debugChildEl = getDebugNode(oldChild);
if (debugEl && debugChildEl && debugEl instanceof DebugElement) {
debugEl.removeChild(debugChildEl);
}
this.delegate.removeChild(parent, oldChild);
};
/**
* @param {?} selectorOrNode
* @return {?}
*/
DebugRenderer2.prototype.selectRootElement = function (selectorOrNode) {
var /** @type {?} */ el = this.delegate.selectRootElement(selectorOrNode);
var /** @type {?} */ debugCtx = getCurrentDebugContext();
if (debugCtx) {
indexDebugNode(new DebugElement(el, null, debugCtx));
}
return el;
};
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @param {?=} namespace
* @return {?}
*/
DebugRenderer2.prototype.setAttribute = function (el, name, value, namespace) {
var /** @type {?} */ debugEl = getDebugNode(el);
if (debugEl && debugEl instanceof DebugElement) {
var /** @type {?} */ fullName = namespace ? namespace + ':' + name : name;
debugEl.attributes[fullName] = value;
}
this.delegate.setAttribute(el, name, value, namespace);
};
/**
* @param {?} el
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
DebugRenderer2.prototype.removeAttribute = function (el, name, namespace) {
var /** @type {?} */ debugEl = getDebugNode(el);
if (debugEl && debugEl instanceof DebugElement) {
var /** @type {?} */ fullName = namespace ? namespace + ':' + name : name;
debugEl.attributes[fullName] = null;
}
this.delegate.removeAttribute(el, name, namespace);
};
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
DebugRenderer2.prototype.addClass = function (el, name) {
var /** @type {?} */ debugEl = getDebugNode(el);
if (debugEl && debugEl instanceof DebugElement) {
debugEl.classes[name] = true;
}
this.delegate.addClass(el, name);
};
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
DebugRenderer2.prototype.removeClass = function (el, name) {
var /** @type {?} */ debugEl = getDebugNode(el);
if (debugEl && debugEl instanceof DebugElement) {
debugEl.classes[name] = false;
}
this.delegate.removeClass(el, name);
};
/**
* @param {?} el
* @param {?} style
* @param {?} value
* @param {?} flags
* @return {?}
*/
DebugRenderer2.prototype.setStyle = function (el, style, value, flags) {
var /** @type {?} */ debugEl = getDebugNode(el);
if (debugEl && debugEl instanceof DebugElement) {
debugEl.styles[style] = value;
}
this.delegate.setStyle(el, style, value, flags);
};
/**
* @param {?} el
* @param {?} style
* @param {?} flags
* @return {?}
*/
DebugRenderer2.prototype.removeStyle = function (el, style, flags) {
var /** @type {?} */ debugEl = getDebugNode(el);
if (debugEl && debugEl instanceof DebugElement) {
debugEl.styles[style] = null;
}
this.delegate.removeStyle(el, style, flags);
};
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
DebugRenderer2.prototype.setProperty = function (el, name, value) {
var /** @type {?} */ debugEl = getDebugNode(el);
if (debugEl && debugEl instanceof DebugElement) {
debugEl.properties[name] = value;
}
this.delegate.setProperty(el, name, value);
};
/**
* @param {?} target
* @param {?} eventName
* @param {?} callback
* @return {?}
*/
DebugRenderer2.prototype.listen = function (target, eventName, callback) {
if (typeof target !== 'string') {
var /** @type {?} */ debugEl = getDebugNode(target);
if (debugEl) {
debugEl.listeners.push(new EventListener(eventName, callback));
}
}
return this.delegate.listen(target, eventName, callback);
};
/**
* @param {?} node
* @return {?}
*/
DebugRenderer2.prototype.parentNode = function (node) { return this.delegate.parentNode(node); };
/**
* @param {?} node
* @return {?}
*/
DebugRenderer2.prototype.nextSibling = function (node) { return this.delegate.nextSibling(node); };
/**
* @param {?} node
* @param {?} value
* @return {?}
*/
DebugRenderer2.prototype.setValue = function (node, value) { return this.delegate.setValue(node, value); };
return DebugRenderer2;
}());
/**
* @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
*/
/**
* @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
*/
/**
* @return {?}
*/
function _iterableDiffersFactory() {
return defaultIterableDiffers;
}
/**
* @return {?}
*/
function _keyValueDiffersFactory() {
return defaultKeyValueDiffers;
}
/**
* @param {?=} locale
* @return {?}
*/
function _localeFactory(locale) {
return locale || 'en-US';
}
/**
* @return {?}
*/
function _initViewEngine() {
initServicesIfNeeded();
}
/**
* This module includes the providers of \@angular/core that are needed
* to bootstrap components via `ApplicationRef`.
*
* \@experimental
*/
var ApplicationModule = (function () {
/**
* @param {?} appRef
*/
function ApplicationModule(appRef) {
}
return ApplicationModule;
}());
ApplicationModule.decorators = [
{ type: NgModule, args: [{
providers: [
ApplicationRef_,
{ provide: ApplicationRef, useExisting: ApplicationRef_ },
ApplicationInitStatus,
Compiler,
APP_ID_RANDOM_PROVIDER,
{ provide: IterableDiffers, useFactory: _iterableDiffersFactory },
{ provide: KeyValueDiffers, useFactory: _keyValueDiffersFactory },
{
provide: LOCALE_ID,
useFactory: _localeFactory,
deps: [[new Inject(LOCALE_ID), new Optional(), new SkipSelf()]]
},
{ provide: APP_INITIALIZER, useValue: _initViewEngine, multi: true },
]
},] },
];
/**
* @nocollapse
*/
ApplicationModule.ctorParameters = function () { return [
{ type: ApplicationRef, },
]; };
/**
* @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
*/
var LifecycleHooks = {};
LifecycleHooks.OnInit = 0;
LifecycleHooks.OnDestroy = 1;
LifecycleHooks.DoCheck = 2;
LifecycleHooks.OnChanges = 3;
LifecycleHooks.AfterContentInit = 4;
LifecycleHooks.AfterContentChecked = 5;
LifecycleHooks.AfterViewInit = 6;
LifecycleHooks.AfterViewChecked = 7;
LifecycleHooks[LifecycleHooks.OnInit] = "OnInit";
LifecycleHooks[LifecycleHooks.OnDestroy] = "OnDestroy";
LifecycleHooks[LifecycleHooks.DoCheck] = "DoCheck";
LifecycleHooks[LifecycleHooks.OnChanges] = "OnChanges";
LifecycleHooks[LifecycleHooks.AfterContentInit] = "AfterContentInit";
LifecycleHooks[LifecycleHooks.AfterContentChecked] = "AfterContentChecked";
LifecycleHooks[LifecycleHooks.AfterViewInit] = "AfterViewInit";
LifecycleHooks[LifecycleHooks.AfterViewChecked] = "AfterViewChecked";
var LIFECYCLE_HOOKS_VALUES = [
LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
LifecycleHooks.AfterViewChecked
];
/**
* @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
*/
/**
* @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
*/
/**
* \@experimental Animation support is experimental.
*/
/**
* `trigger` is an animation-specific function that is designed to be used inside of Angular's
* animation DSL language. If this information is new, please navigate to the {\@link
* Component#animations-anchor component animations metadata page} to gain a better understanding of
* how animations in Angular are used.
*
* `trigger` Creates an animation trigger which will a list of {\@link state state} and {\@link
* transition transition} entries that will be evaluated when the expression bound to the trigger
* changes.
*
* Triggers are registered within the component annotation data under the {\@link
* Component#animations-anchor animations section}. An animation trigger can be placed on an element
* within a template by referencing the name of the trigger followed by the expression value that the
* trigger is bound to (in the form of `[\@triggerName]="expression"`.
*
* ### Usage
*
* `trigger` will create an animation trigger reference based on the provided `name` value. The
* provided `animation` value is expected to be an array consisting of {\@link state state} and {\@link
* transition transition} declarations.
*
* ```typescript
* \@Component({
* selector: 'my-component',
* templateUrl: 'my-component-tpl.html',
* animations: [
* trigger("myAnimationTrigger", [
* state(...),
* state(...),
* transition(...),
* transition(...)
* ])
* ]
* })
* class MyComponent {
* myStatusExp = "something";
* }
* ```
*
* The template associated with this component will make use of the `myAnimationTrigger` animation
* trigger by binding to an element within its template code.
*
* ```html
* <!-- somewhere inside of my-component-tpl.html -->
* <div [\@myAnimationTrigger]="myStatusExp">...</div>
* tools/gulp-tasks/validate-commit-message.js ```
*
* {\@example core/animation/ts/dsl/animation_example.ts region='Component'}
*
* \@experimental Animation support is experimental.
* @param {?} name
* @param {?} definitions
* @return {?}
*/
function trigger$1(name, definitions) {
return { name: name, definitions: definitions };
}
/**
* `animate` is an animation-specific function that is designed to be used inside of Angular's
* animation DSL language. If this information is new, please navigate to the {\@link
* Component#animations-anchor component animations metadata page} to gain a better understanding of
* how animations in Angular are used.
*
* `animate` specifies an animation step that will apply the provided `styles` data for a given
* amount of time based on the provided `timing` expression value. Calls to `animate` are expected
* to be used within {\@link sequence an animation sequence}, {\@link group group}, or {\@link
* transition transition}.
*
* ### Usage
*
* The `animate` function accepts two input parameters: `timing` and `styles`:
*
* - `timing` is a string based value that can be a combination of a duration with optional delay
* and easing values. The format for the expression breaks down to `duration delay easing`
* (therefore a value such as `1s 100ms ease-out` will be parse itself into `duration=1000,
* delay=100, easing=ease-out`. If a numeric value is provided then that will be used as the
* `duration` value in millisecond form.
* - `styles` is the style input data which can either be a call to {\@link style style} or {\@link
* keyframes keyframes}. If left empty then the styles from the destination state will be collected
* and used (this is useful when describing an animation step that will complete an animation by
* {\@link transition#the-final-animate-call animating to the final state}).
*
* ```typescript
* // various functions for specifying timing data
* animate(500, style(...))
* animate("1s", style(...))
* animate("100ms 0.5s", style(...))
* animate("5s ease", style(...))
* animate("5s 10ms cubic-bezier(.17,.67,.88,.1)", style(...))
*
* // either style() of keyframes() can be used
* animate(500, style({ background: "red" }))
* animate(500, keyframes([
* style({ background: "blue" })),
* style({ background: "red" }))
* ])
* ```
*
* {\@example core/animation/ts/dsl/animation_example.ts region='Component'}
*
* \@experimental Animation support is experimental.
* @param {?} timings
* @param {?=} styles
* @return {?}
*/
function animate$1(timings, styles) {
if (styles === void 0) { styles = null; }
return { type: 4 /* Animate */, styles: styles, timings: timings };
}
/**
* `group` is an animation-specific function that is designed to be used inside of Angular's
* animation DSL language. If this information is new, please navigate to the {\@link
* Component#animations-anchor component animations metadata page} to gain a better understanding of
* how animations in Angular are used.
*
* `group` specifies a list of animation steps that are all run in parallel. Grouped animations are
* useful when a series of styles must be animated/closed off at different statrting/ending times.
*
* The `group` function can either be used within a {\@link sequence sequence} or a {\@link transition
* transition} and it will only continue to the next instruction once all of the inner animation
* steps have completed.
*
* ### Usage
*
* The `steps` data that is passed into the `group` animation function can either consist of {\@link
* style style} or {\@link animate animate} function calls. Each call to `style()` or `animate()`
* within a group will be executed instantly (use {\@link keyframes keyframes} or a {\@link
* animate#usage animate() with a delay value} to offset styles to be applied at a later time).
*
* ```typescript
* group([
* animate("1s", { background: "black" }))
* animate("2s", { color: "white" }))
* ])
* ```
*
* {\@example core/animation/ts/dsl/animation_example.ts region='Component'}
*
* \@experimental Animation support is experimental.
* @param {?} steps
* @return {?}
*/
function group$1(steps) {
return { type: 3 /* Group */, steps: steps };
}
/**
* `sequence` is an animation-specific function that is designed to be used inside of Angular's
* animation DSL language. If this information is new, please navigate to the {\@link
* Component#animations-anchor component animations metadata page} to gain a better understanding of
* how animations in Angular are used.
*
* `sequence` Specifies a list of animation steps that are run one by one. (`sequence` is used by
* default when an array is passed as animation data into {\@link transition transition}.)
*
* The `sequence` function can either be used within a {\@link group group} or a {\@link transition
* transition} and it will only continue to the next instruction once each of the inner animation
* steps have completed.
*
* To perform animation styling in parallel with other animation steps then have a look at the
* {\@link group group} animation function.
*
* ### Usage
*
* The `steps` data that is passed into the `sequence` animation function can either consist of
* {\@link style style} or {\@link animate animate} function calls. A call to `style()` will apply the
* provided styling data immediately while a call to `animate()` will apply its styling data over a
* given time depending on its timing data.
*
* ```typescript
* sequence([
* style({ opacity: 0 })),
* animate("1s", { opacity: 1 }))
* ])
* ```
*
* {\@example core/animation/ts/dsl/animation_example.ts region='Component'}
*
* \@experimental Animation support is experimental.
* @param {?} steps
* @return {?}
*/
function sequence$1(steps) {
return { type: 2 /* Sequence */, steps: steps };
}
/**
* `style` is an animation-specific function that is designed to be used inside of Angular's
* animation DSL language. If this information is new, please navigate to the {\@link
* Component#animations-anchor component animations metadata page} to gain a better understanding of
* how animations in Angular are used.
*
* `style` declares a key/value object containing CSS properties/styles that can then be used for
* {\@link state animation states}, within an {\@link sequence animation sequence}, or as styling data
* for both {\@link animate animate} and {\@link keyframes keyframes}.
*
* ### Usage
*
* `style` takes in a key/value string map as data and expects one or more CSS property/value pairs
* to be defined.
*
* ```typescript
* // string values are used for css properties
* style({ background: "red", color: "blue" })
*
* // numerical (pixel) values are also supported
* style({ width: 100, height: 0 })
* ```
*
* #### Auto-styles (using `*`)
*
* When an asterix (`*`) character is used as a value then it will be detected from the element
* being animated and applied as animation data when the animation starts.
*
* This feature proves useful for a state depending on layout and/or environment factors; in such
* cases the styles are calculated just before the animation starts.
*
* ```typescript
* // the steps below will animate from 0 to the
* // actual height of the element
* style({ height: 0 }),
* animate("1s", style({ height: "*" }))
* ```
*
* {\@example core/animation/ts/dsl/animation_example.ts region='Component'}
*
* \@experimental Animation support is experimental.
* @param {?} tokens
* @return {?}
*/
function style$1(tokens) {
return { type: 6 /* Style */, styles: tokens };
}
/**
* `state` is an animation-specific function that is designed to be used inside of Angular's
* animation DSL language. If this information is new, please navigate to the {\@link
* Component#animations-anchor component animations metadata page} to gain a better understanding of
* how animations in Angular are used.
*
* `state` declares an animation state within the given trigger. When a state is active within a
* component then its associated styles will persist on the element that the trigger is attached to
* (even when the animation ends).
*
* To animate between states, have a look at the animation {\@link transition transition} DSL
* function. To register states to an animation trigger please have a look at the {\@link trigger
* trigger} function.
*
* #### The `void` state
*
* The `void` state value is a reserved word that angular uses to determine when the element is not
* apart of the application anymore (e.g. when an `ngIf` evaluates to false then the state of the
* associated element is void).
*
* #### The `*` (default) state
*
* The `*` state (when styled) is a fallback state that will be used if the state that is being
* animated is not declared within the trigger.
*
* ### Usage
*
* `state` will declare an animation state with its associated styles
* within the given trigger.
*
* - `stateNameExpr` can be one or more state names separated by commas.
* - `styles` refers to the {\@link style styling data} that will be persisted on the element once
* the state has been reached.
*
* ```typescript
* // "void" is a reserved name for a state and is used to represent
* // the state in which an element is detached from from the application.
* state("void", style({ height: 0 }))
*
* // user-defined states
* state("closed", style({ height: 0 }))
* state("open, visible", style({ height: "*" }))
* ```
*
* {\@example core/animation/ts/dsl/animation_example.ts region='Component'}
*
* \@experimental Animation support is experimental.
* @param {?} name
* @param {?} styles
* @return {?}
*/
function state$1(name, styles) {
return { type: 0 /* State */, name: name, styles: styles };
}
/**
* `keyframes` is an animation-specific function that is designed to be used inside of Angular's
* animation DSL language. If this information is new, please navigate to the {\@link
* Component#animations-anchor component animations metadata page} to gain a better understanding of
* how animations in Angular are used.
*
* `keyframes` specifies a collection of {\@link style style} entries each optionally characterized
* by an `offset` value.
*
* ### Usage
*
* The `keyframes` animation function is designed to be used alongside the {\@link animate animate}
* animation function. Instead of applying animations from where they are currently to their
* destination, keyframes can describe how each style entry is applied and at what point within the
* animation arc (much like CSS Keyframe Animations do).
*
* For each `style()` entry an `offset` value can be set. Doing so allows to specifiy at what
* percentage of the animate time the styles will be applied.
*
* ```typescript
* // the provided offset values describe when each backgroundColor value is applied.
* animate("5s", keyframes([
* style({ backgroundColor: "red", offset: 0 }),
* style({ backgroundColor: "blue", offset: 0.2 }),
* style({ backgroundColor: "orange", offset: 0.3 }),
* style({ backgroundColor: "black", offset: 1 })
* ]))
* ```
*
* Alternatively, if there are no `offset` values used within the style entries then the offsets
* will be calculated automatically.
*
* ```typescript
* animate("5s", keyframes([
* style({ backgroundColor: "red" }) // offset = 0
* style({ backgroundColor: "blue" }) // offset = 0.33
* style({ backgroundColor: "orange" }) // offset = 0.66
* style({ backgroundColor: "black" }) // offset = 1
* ]))
* ```
*
* {\@example core/animation/ts/dsl/animation_example.ts region='Component'}
*
* \@experimental Animation support is experimental.
* @param {?} steps
* @return {?}
*/
function keyframes$1(steps) {
return { type: 5 /* KeyframeSequence */, steps: steps };
}
/**
* `transition` is an animation-specific function that is designed to be used inside of Angular's
* animation DSL language. If this information is new, please navigate to the {\@link
* Component#animations-anchor component animations metadata page} to gain a better understanding of
* how animations in Angular are used.
*
* `transition` declares the {\@link sequence sequence of animation steps} that will be run when the
* provided `stateChangeExpr` value is satisfied. The `stateChangeExpr` consists of a `state1 =>
* state2` which consists of two known states (use an asterix (`*`) to refer to a dynamic starting
* and/or ending state).
*
* A function can also be provided as the `stateChangeExpr` argument for a transition and this
* function will be executed each time a state change occurs. If the value returned within the
* function is true then the associated animation will be run.
*
* Animation transitions are placed within an {\@link trigger animation trigger}. For an transition
* to animate to a state value and persist its styles then one or more {\@link state animation
* states} is expected to be defined.
*
* ### Usage
*
* An animation transition is kicked off the `stateChangeExpr` predicate evaluates to true based on
* what the previous state is and what the current state has become. In other words, if a transition
* is defined that matches the old/current state criteria then the associated animation will be
* triggered.
*
* ```typescript
* // all transition/state changes are defined within an animation trigger
* trigger("myAnimationTrigger", [
* // if a state is defined then its styles will be persisted when the
* // animation has fully completed itself
* state("on", style({ background: "green" })),
* state("off", style({ background: "grey" })),
*
* // a transition animation that will be kicked off when the state value
* // bound to "myAnimationTrigger" changes from "on" to "off"
* transition("on => off", animate(500)),
*
* // it is also possible to do run the same animation for both directions
* transition("on <=> off", animate(500)),
*
* // or to define multiple states pairs separated by commas
* transition("on => off, off => void", animate(500)),
*
* // this is a catch-all state change for when an element is inserted into
* // the page and the destination state is unknown
* transition("void => *", [
* style({ opacity: 0 }),
* animate(500)
* ]),
*
* // this will capture a state change between any states
* transition("* => *", animate("1s 0s")),
*
* // you can also go full out and include a function
* transition((fromState, toState) => {
* // when `true` then it will allow the animation below to be invoked
* return fromState == "off" && toState == "on";
* }, animate("1s 0s"))
* ])
* ```
*
* The template associated with this component will make use of the `myAnimationTrigger` animation
* trigger by binding to an element within its template code.
*
* ```html
* <!-- somewhere inside of my-component-tpl.html -->
* <div [\@myAnimationTrigger]="myStatusExp">...</div>
* ```
*
* #### The final `animate` call
*
* If the final step within the transition steps is a call to `animate()` that **only** uses a
* timing value with **no style data** then it will be automatically used as the final animation arc
* for the element to animate itself to the final state. This involves an automatic mix of
* adding/removing CSS styles so that the element will be in the exact state it should be for the
* applied state to be presented correctly.
*
* ```
* // start off by hiding the element, but make sure that it animates properly to whatever state
* // is currently active for "myAnimationTrigger"
* transition("void => *", [
* style({ opacity: 0 }),
* animate(500)
* ])
* ```
*
* ### Transition Aliases (`:enter` and `:leave`)
*
* Given that enter (insertion) and leave (removal) animations are so common, the `transition`
* function accepts both `:enter` and `:leave` values which are aliases for the `void => *` and `*
* => void` state changes.
*
* ```
* transition(":enter", [
* style({ opacity: 0 }),
* animate(500, style({ opacity: 1 }))
* ])
* transition(":leave", [
* animate(500, style({ opacity: 0 }))
* ])
* ```
*
* {\@example core/animation/ts/dsl/animation_example.ts region='Component'}
*
* \@experimental Animation support is experimental.
* @param {?} stateChangeExpr
* @param {?} steps
* @return {?}
*/
function transition$1(stateChangeExpr, steps) {
return { type: 1 /* Transition */, expr: stateChangeExpr, animation: steps };
}
/**
* @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
*/
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
*/
var AUTO_STYLE$$1 = '*';
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
* @param {?} name
* @param {?} definitions
* @return {?}
*/
function trigger$$1(name, definitions) {
return trigger$1(name, definitions);
}
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
* @param {?} timings
* @param {?=} styles
* @return {?}
*/
function animate$$1(timings, styles) {
return animate$1(timings, styles);
}
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
* @param {?} steps
* @return {?}
*/
function group$$1(steps) {
return group$1(steps);
}
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
* @param {?} steps
* @return {?}
*/
function sequence$$1(steps) {
return sequence$1(steps);
}
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
* @param {?} tokens
* @return {?}
*/
function style$$1(tokens) {
return style$1(tokens);
}
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
* @param {?} name
* @param {?} styles
* @return {?}
*/
function state$$1(name, styles) {
return state$1(name, styles);
}
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
* @param {?} steps
* @return {?}
*/
function keyframes$$1(steps) {
return keyframes$1(steps);
}
/**
* @deprecated This symbol has moved. Please Import from \@angular/animations instead!
* @param {?} stateChangeExpr
* @param {?} steps
* @return {?}
*/
function transition$$1(stateChangeExpr, steps) {
return transition$1(stateChangeExpr, steps);
}
/**
* @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
*/
/**
* @module
* @description
* Entry point from which you should import all public core APIs.
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the core package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=core.es5.js.map
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(21)))
/***/ }),
/* 2 */,
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer) {/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function(useSourceMap) {
var list = [];
// return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if(item[2]) {
return "@media " + item[2] + "{" + content + "}";
} else {
return content;
}
}).join("");
};
// import a list of modules into the list
list.i = function(modules, mediaQuery) {
if(typeof modules === "string")
modules = [[null, modules, ""]];
var alreadyImportedModules = {};
for(var i = 0; i < this.length; i++) {
var id = this[i][0];
if(typeof id === "number")
alreadyImportedModules[id] = true;
}
for(i = 0; i < modules.length; i++) {
var item = modules[i];
// skip already imported module
// this implementation is not 100% perfect for weird media query combinations
// when a module is imported multiple times with different media queries.
// I hope this will never occur (Hey this way we have smaller bundles)
if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
if(mediaQuery && !item[2]) {
item[2] = mediaQuery;
} else if(mediaQuery) {
item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
}
list.push(item);
}
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || '';
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap) {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */'
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
}
// Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
var base64 = new Buffer(JSON.stringify(sourceMap)).toString('base64');
var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
return '/*# ' + data + ' */';
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55).Buffer))
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_common__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__ = __webpack_require__(36);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_rxjs_Subject__ = __webpack_require__(25);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_rxjs_Subject___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_rxjs_Subject__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__ = __webpack_require__(107);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__ = __webpack_require__(110);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_rxjs_operator_concatMap__ = __webpack_require__(305);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_rxjs_operator_concatMap___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_6_rxjs_operator_concatMap__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_rxjs_operator_every__ = __webpack_require__(310);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_rxjs_operator_every___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_7_rxjs_operator_every__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_rxjs_operator_first__ = __webpack_require__(311);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_rxjs_operator_first___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8_rxjs_operator_first__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__ = __webpack_require__(76);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__ = __webpack_require__(78);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11_rxjs_operator_reduce__ = __webpack_require__(316);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11_rxjs_operator_reduce___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_11_rxjs_operator_reduce__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12_rxjs_Observable__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12_rxjs_Observable___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_12_rxjs_Observable__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13_rxjs_operator_catch__ = __webpack_require__(303);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13_rxjs_operator_catch___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_13_rxjs_operator_catch__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14_rxjs_operator_concatAll__ = __webpack_require__(304);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14_rxjs_operator_concatAll___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_14_rxjs_operator_concatAll__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15_rxjs_util_EmptyError__ = __webpack_require__(82);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15_rxjs_util_EmptyError___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_15_rxjs_util_EmptyError__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16_rxjs_observable_fromPromise__ = __webpack_require__(108);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16_rxjs_observable_fromPromise___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_16_rxjs_observable_fromPromise__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17_rxjs_operator_last__ = __webpack_require__(312);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17_rxjs_operator_last___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_17_rxjs_operator_last__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18_rxjs_operator_mergeAll__ = __webpack_require__(77);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18_rxjs_operator_mergeAll___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_18_rxjs_operator_mergeAll__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__angular_platform_browser__ = __webpack_require__(22);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20_rxjs_operator_filter__ = __webpack_require__(111);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20_rxjs_operator_filter___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_20_rxjs_operator_filter__);
/* unused harmony export RouterLink */
/* unused harmony export RouterLinkWithHref */
/* unused harmony export RouterLinkActive */
/* unused harmony export RouterOutlet */
/* unused harmony export NavigationCancel */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return NavigationEnd; });
/* unused harmony export NavigationError */
/* unused harmony export NavigationStart */
/* unused harmony export RouteConfigLoadEnd */
/* unused harmony export RouteConfigLoadStart */
/* unused harmony export RoutesRecognized */
/* unused harmony export RouteReuseStrategy */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Router; });
/* unused harmony export ROUTES */
/* unused harmony export ROUTER_CONFIGURATION */
/* unused harmony export ROUTER_INITIALIZER */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return RouterModule; });
/* unused harmony export provideRoutes */
/* unused harmony export RouterOutletMap */
/* unused harmony export NoPreloading */
/* unused harmony export PreloadAllModules */
/* unused harmony export PreloadingStrategy */
/* unused harmony export RouterPreloader */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return ActivatedRoute; });
/* unused harmony export ActivatedRouteSnapshot */
/* unused harmony export RouterState */
/* unused harmony export RouterStateSnapshot */
/* unused harmony export PRIMARY_OUTLET */
/* unused harmony export convertToParamMap */
/* unused harmony export UrlHandlingStrategy */
/* unused harmony export DefaultUrlSerializer */
/* unused harmony export UrlSegment */
/* unused harmony export UrlSegmentGroup */
/* unused harmony export UrlSerializer */
/* unused harmony export UrlTree */
/* unused harmony export VERSION */
/* unused harmony export ɵROUTER_PROVIDERS */
/* unused harmony export ɵflatten */
/* unused harmony export ɵa */
/* unused harmony export ɵg */
/* unused harmony export ɵh */
/* unused harmony export ɵi */
/* unused harmony export ɵd */
/* unused harmony export ɵc */
/* unused harmony export ɵj */
/* unused harmony export ɵf */
/* unused harmony export ɵb */
/* unused harmony export ɵe */
/* unused harmony export ɵk */
/* unused harmony export ɵl */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.1
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @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
*/
/**
* \@whatItDoes Represents an event triggered when a navigation starts.
*
* \@stable
*/
var NavigationStart = (function () {
/**
* @param {?} id
* @param {?} url
*/
function NavigationStart(id, url) {
this.id = id;
this.url = url;
}
/**
* \@docsNotRequired
* @return {?}
*/
NavigationStart.prototype.toString = function () { return "NavigationStart(id: " + this.id + ", url: '" + this.url + "')"; };
return NavigationStart;
}());
/**
* \@whatItDoes Represents an event triggered when a navigation ends successfully.
*
* \@stable
*/
var NavigationEnd = (function () {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
*/
function NavigationEnd(id, url, urlAfterRedirects) {
this.id = id;
this.url = url;
this.urlAfterRedirects = urlAfterRedirects;
}
/**
* \@docsNotRequired
* @return {?}
*/
NavigationEnd.prototype.toString = function () {
return "NavigationEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "')";
};
return NavigationEnd;
}());
/**
* \@whatItDoes Represents an event triggered when a navigation is canceled.
*
* \@stable
*/
var NavigationCancel = (function () {
/**
* @param {?} id
* @param {?} url
* @param {?} reason
*/
function NavigationCancel(id, url, reason) {
this.id = id;
this.url = url;
this.reason = reason;
}
/**
* \@docsNotRequired
* @return {?}
*/
NavigationCancel.prototype.toString = function () { return "NavigationCancel(id: " + this.id + ", url: '" + this.url + "')"; };
return NavigationCancel;
}());
/**
* \@whatItDoes Represents an event triggered when a navigation fails due to an unexpected error.
*
* \@stable
*/
var NavigationError = (function () {
/**
* @param {?} id
* @param {?} url
* @param {?} error
*/
function NavigationError(id, url, error) {
this.id = id;
this.url = url;
this.error = error;
}
/**
* \@docsNotRequired
* @return {?}
*/
NavigationError.prototype.toString = function () {
return "NavigationError(id: " + this.id + ", url: '" + this.url + "', error: " + this.error + ")";
};
return NavigationError;
}());
/**
* \@whatItDoes Represents an event triggered when routes are recognized.
*
* \@stable
*/
var RoutesRecognized = (function () {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
* @param {?} state
*/
function RoutesRecognized(id, url, urlAfterRedirects, state) {
this.id = id;
this.url = url;
this.urlAfterRedirects = urlAfterRedirects;
this.state = state;
}
/**
* \@docsNotRequired
* @return {?}
*/
RoutesRecognized.prototype.toString = function () {
return "RoutesRecognized(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
};
return RoutesRecognized;
}());
/**
* \@whatItDoes Represents an event triggered before lazy loading a route config.
*
* \@experimental
*/
var RouteConfigLoadStart = (function () {
/**
* @param {?} route
*/
function RouteConfigLoadStart(route) {
this.route = route;
}
/**
* @return {?}
*/
RouteConfigLoadStart.prototype.toString = function () { return "RouteConfigLoadStart(path: " + this.route.path + ")"; };
return RouteConfigLoadStart;
}());
/**
* \@whatItDoes Represents an event triggered when a route has been lazy loaded.
*
* \@experimental
*/
var RouteConfigLoadEnd = (function () {
/**
* @param {?} route
*/
function RouteConfigLoadEnd(route) {
this.route = route;
}
/**
* @return {?}
*/
RouteConfigLoadEnd.prototype.toString = function () { return "RouteConfigLoadEnd(path: " + this.route.path + ")"; };
return RouteConfigLoadEnd;
}());
/**
* @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
*/
/**
* \@whatItDoes Name of the primary outlet.
*
* \@stable
*/
var PRIMARY_OUTLET = 'primary';
var ParamsAsMap = (function () {
/**
* @param {?} params
*/
function ParamsAsMap(params) {
this.params = params || {};
}
/**
* @param {?} name
* @return {?}
*/
ParamsAsMap.prototype.has = function (name) { return this.params.hasOwnProperty(name); };
/**
* @param {?} name
* @return {?}
*/
ParamsAsMap.prototype.get = function (name) {
if (this.has(name)) {
var /** @type {?} */ v = this.params[name];
return Array.isArray(v) ? v[0] : v;
}
return null;
};
/**
* @param {?} name
* @return {?}
*/
ParamsAsMap.prototype.getAll = function (name) {
if (this.has(name)) {
var /** @type {?} */ v = this.params[name];
return Array.isArray(v) ? v : [v];
}
return [];
};
Object.defineProperty(ParamsAsMap.prototype, "keys", {
/**
* @return {?}
*/
get: function () { return Object.keys(this.params); },
enumerable: true,
configurable: true
});
return ParamsAsMap;
}());
/**
* Convert a {\@link Params} instance to a {\@link ParamMap}.
*
* \@stable
* @param {?} params
* @return {?}
*/
function convertToParamMap(params) {
return new ParamsAsMap(params);
}
var NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
/**
* @param {?} message
* @return {?}
*/
function navigationCancelingError(message) {
var /** @type {?} */ error = Error('NavigationCancelingError: ' + message);
((error))[NAVIGATION_CANCELING_ERROR] = true;
return error;
}
/**
* @param {?} error
* @return {?}
*/
function isNavigationCancelingError(error) {
return ((error))[NAVIGATION_CANCELING_ERROR];
}
/**
* @param {?} segments
* @param {?} segmentGroup
* @param {?} route
* @return {?}
*/
function defaultUrlMatcher(segments, segmentGroup, route) {
var /** @type {?} */ parts = ((route.path)).split('/');
if (parts.length > segments.length) {
// The actual URL is shorter than the config, no match
return null;
}
if (route.pathMatch === 'full' &&
(segmentGroup.hasChildren() || parts.length < segments.length)) {
// The config is longer than the actual URL but we are looking for a full match, return null
return null;
}
var /** @type {?} */ posParams = {};
// Check each config part against the actual URL
for (var /** @type {?} */ index = 0; index < parts.length; index++) {
var /** @type {?} */ part = parts[index];
var /** @type {?} */ segment = segments[index];
var /** @type {?} */ isParameter = part.startsWith(':');
if (isParameter) {
posParams[part.substring(1)] = segment;
}
else if (part !== segment.path) {
// The actual URL part does not match the config, no match
return null;
}
}
return { consumed: segments.slice(0, parts.length), posParams: posParams };
}
/**
* @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
*/
var LoadedRouterConfig = (function () {
/**
* @param {?} routes
* @param {?} module
*/
function LoadedRouterConfig(routes, module) {
this.routes = routes;
this.module = module;
}
return LoadedRouterConfig;
}());
/**
* @param {?} config
* @param {?=} parentPath
* @return {?}
*/
function validateConfig(config, parentPath) {
if (parentPath === void 0) { parentPath = ''; }
// forEach doesn't iterate undefined values
for (var /** @type {?} */ i = 0; i < config.length; i++) {
var /** @type {?} */ route = config[i];
var /** @type {?} */ fullPath = getFullPath(parentPath, route);
validateNode(route, fullPath);
}
}
/**
* @param {?} route
* @param {?} fullPath
* @return {?}
*/
function validateNode(route, fullPath) {
if (!route) {
throw new Error("\n Invalid configuration of route '" + fullPath + "': Encountered undefined route.\n The reason might be an extra comma.\n\n Example:\n const routes: Routes = [\n { path: '', redirectTo: '/dashboard', pathMatch: 'full' },\n { path: 'dashboard', component: DashboardComponent },, << two commas\n { path: 'detail/:id', component: HeroDetailComponent }\n ];\n ");
}
if (Array.isArray(route)) {
throw new Error("Invalid configuration of route '" + fullPath + "': Array cannot be specified");
}
if (!route.component && (route.outlet && route.outlet !== PRIMARY_OUTLET)) {
throw new Error("Invalid configuration of route '" + fullPath + "': a componentless route cannot have a named outlet set");
}
if (route.redirectTo && route.children) {
throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and children cannot be used together");
}
if (route.redirectTo && route.loadChildren) {
throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and loadChildren cannot be used together");
}
if (route.children && route.loadChildren) {
throw new Error("Invalid configuration of route '" + fullPath + "': children and loadChildren cannot be used together");
}
if (route.redirectTo && route.component) {
throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and component cannot be used together");
}
if (route.path && route.matcher) {
throw new Error("Invalid configuration of route '" + fullPath + "': path and matcher cannot be used together");
}
if (route.redirectTo === void 0 && !route.component && !route.children && !route.loadChildren) {
throw new Error("Invalid configuration of route '" + fullPath + "'. One of the following must be provided: component, redirectTo, children or loadChildren");
}
if (route.path === void 0 && route.matcher === void 0) {
throw new Error("Invalid configuration of route '" + fullPath + "': routes must have either a path or a matcher specified");
}
if (typeof route.path === 'string' && route.path.charAt(0) === '/') {
throw new Error("Invalid configuration of route '" + fullPath + "': path cannot start with a slash");
}
if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {
var /** @type {?} */ exp = "The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.";
throw new Error("Invalid configuration of route '{path: \"" + fullPath + "\", redirectTo: \"" + route.redirectTo + "\"}': please provide 'pathMatch'. " + exp);
}
if (route.pathMatch !== void 0 && route.pathMatch !== 'full' && route.pathMatch !== 'prefix') {
throw new Error("Invalid configuration of route '" + fullPath + "': pathMatch can only be set to 'prefix' or 'full'");
}
if (route.children) {
validateConfig(route.children, fullPath);
}
}
/**
* @param {?} parentPath
* @param {?} currentRoute
* @return {?}
*/
function getFullPath(parentPath, currentRoute) {
if (!currentRoute) {
return parentPath;
}
if (!parentPath && !currentRoute.path) {
return '';
}
else if (parentPath && !currentRoute.path) {
return parentPath + "/";
}
else if (!parentPath && currentRoute.path) {
return currentRoute.path;
}
else {
return parentPath + "/" + currentRoute.path;
}
}
/**
* @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
*/
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function shallowEqualArrays(a, b) {
if (a.length !== b.length)
return false;
for (var /** @type {?} */ i = 0; i < a.length; ++i) {
if (!shallowEqual(a[i], b[i]))
return false;
}
return true;
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function shallowEqual(a, b) {
var /** @type {?} */ k1 = Object.keys(a);
var /** @type {?} */ k2 = Object.keys(b);
if (k1.length != k2.length) {
return false;
}
var /** @type {?} */ key;
for (var /** @type {?} */ i = 0; i < k1.length; i++) {
key = k1[i];
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
/**
* @template T
* @param {?} arr
* @return {?}
*/
function flatten(arr) {
return Array.prototype.concat.apply([], arr);
}
/**
* @template T
* @param {?} a
* @return {?}
*/
function last$1(a) {
return a.length > 0 ? a[a.length - 1] : null;
}
/**
* @param {?} bools
* @return {?}
*/
/**
* @template K, V
* @param {?} map
* @param {?} callback
* @return {?}
*/
function forEach(map$$1, callback) {
for (var /** @type {?} */ prop in map$$1) {
if (map$$1.hasOwnProperty(prop)) {
callback(map$$1[prop], prop);
}
}
}
/**
* @template A, B
* @param {?} obj
* @param {?} fn
* @return {?}
*/
function waitForMap(obj, fn) {
if (Object.keys(obj).length === 0) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])({});
}
var /** @type {?} */ waitHead = [];
var /** @type {?} */ waitTail = [];
var /** @type {?} */ res = {};
forEach(obj, function (a, k) {
var /** @type {?} */ mapped = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(fn(k, a), function (r) { return res[k] = r; });
if (k === PRIMARY_OUTLET) {
waitHead.push(mapped);
}
else {
waitTail.push(mapped);
}
});
var /** @type {?} */ concat$ = __WEBPACK_IMPORTED_MODULE_14_rxjs_operator_concatAll__["concatAll"].call(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"].apply(void 0, waitHead.concat(waitTail)));
var /** @type {?} */ last$ = __WEBPACK_IMPORTED_MODULE_17_rxjs_operator_last__["last"].call(concat$);
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(last$, function () { return res; });
}
/**
* @param {?} observables
* @return {?}
*/
function andObservables(observables) {
var /** @type {?} */ merged$ = __WEBPACK_IMPORTED_MODULE_18_rxjs_operator_mergeAll__["mergeAll"].call(observables);
return __WEBPACK_IMPORTED_MODULE_7_rxjs_operator_every__["every"].call(merged$, function (result) { return result === true; });
}
/**
* @template T
* @param {?} value
* @return {?}
*/
function wrapIntoObservable(value) {
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["g" /* ɵisObservable */])(value)) {
return value;
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["f" /* ɵisPromise */])(value)) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_16_rxjs_observable_fromPromise__["fromPromise"])(value);
}
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(value);
}
/**
* @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
*/
/**
* @return {?}
*/
function createEmptyUrlTree() {
return new UrlTree(new UrlSegmentGroup([], {}), {}, null);
}
/**
* @param {?} container
* @param {?} containee
* @param {?} exact
* @return {?}
*/
function containsTree(container, containee, exact) {
if (exact) {
return equalQueryParams(container.queryParams, containee.queryParams) &&
equalSegmentGroups(container.root, containee.root);
}
return containsQueryParams(container.queryParams, containee.queryParams) &&
containsSegmentGroup(container.root, containee.root);
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function equalQueryParams(container, containee) {
return shallowEqual(container, containee);
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function equalSegmentGroups(container, containee) {
if (!equalPath(container.segments, containee.segments))
return false;
if (container.numberOfChildren !== containee.numberOfChildren)
return false;
for (var /** @type {?} */ c in containee.children) {
if (!container.children[c])
return false;
if (!equalSegmentGroups(container.children[c], containee.children[c]))
return false;
}
return true;
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function containsQueryParams(container, containee) {
return Object.keys(containee).length <= Object.keys(container).length &&
Object.keys(containee).every(function (key) { return containee[key] === container[key]; });
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function containsSegmentGroup(container, containee) {
return containsSegmentGroupHelper(container, containee, containee.segments);
}
/**
* @param {?} container
* @param {?} containee
* @param {?} containeePaths
* @return {?}
*/
function containsSegmentGroupHelper(container, containee, containeePaths) {
if (container.segments.length > containeePaths.length) {
var /** @type {?} */ current = container.segments.slice(0, containeePaths.length);
if (!equalPath(current, containeePaths))
return false;
if (containee.hasChildren())
return false;
return true;
}
else if (container.segments.length === containeePaths.length) {
if (!equalPath(container.segments, containeePaths))
return false;
for (var /** @type {?} */ c in containee.children) {
if (!container.children[c])
return false;
if (!containsSegmentGroup(container.children[c], containee.children[c]))
return false;
}
return true;
}
else {
var /** @type {?} */ current = containeePaths.slice(0, container.segments.length);
var /** @type {?} */ next = containeePaths.slice(container.segments.length);
if (!equalPath(container.segments, current))
return false;
if (!container.children[PRIMARY_OUTLET])
return false;
return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next);
}
}
/**
* \@whatItDoes Represents the parsed URL.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const tree: UrlTree =
* router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
* const f = tree.fragment; // return 'fragment'
* const q = tree.queryParams; // returns {debug: 'true'}
* const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
* const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
* g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
* g.children['support'].segments; // return 1 segment 'help'
* }
* }
* ```
*
* \@description
*
* Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
* serialized tree.
* UrlTree is a data structure that provides a lot of affordances in dealing with URLs
*
* \@stable
*/
var UrlTree = (function () {
/**
* \@internal
* @param {?} root
* @param {?} queryParams
* @param {?} fragment
*/
function UrlTree(root, queryParams, fragment) {
this.root = root;
this.queryParams = queryParams;
this.fragment = fragment;
}
Object.defineProperty(UrlTree.prototype, "queryParamMap", {
/**
* @return {?}
*/
get: function () {
if (!this._queryParamMap) {
this._queryParamMap = convertToParamMap(this.queryParams);
}
return this._queryParamMap;
},
enumerable: true,
configurable: true
});
/**
* \@docsNotRequired
* @return {?}
*/
UrlTree.prototype.toString = function () { return DEFAULT_SERIALIZER.serialize(this); };
return UrlTree;
}());
/**
* \@whatItDoes Represents the parsed URL segment group.
*
* See {\@link UrlTree} for more information.
*
* \@stable
*/
var UrlSegmentGroup = (function () {
/**
* @param {?} segments
* @param {?} children
*/
function UrlSegmentGroup(segments, children) {
var _this = this;
this.segments = segments;
this.children = children;
/** The parent node in the url tree */
this.parent = null;
forEach(children, function (v, k) { return v.parent = _this; });
}
/**
* Wether the segment has child segments
* @return {?}
*/
UrlSegmentGroup.prototype.hasChildren = function () { return this.numberOfChildren > 0; };
Object.defineProperty(UrlSegmentGroup.prototype, "numberOfChildren", {
/**
* Number of child segments
* @return {?}
*/
get: function () { return Object.keys(this.children).length; },
enumerable: true,
configurable: true
});
/**
* \@docsNotRequired
* @return {?}
*/
UrlSegmentGroup.prototype.toString = function () { return serializePaths(this); };
return UrlSegmentGroup;
}());
/**
* \@whatItDoes Represents a single URL segment.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const tree: UrlTree = router.parseUrl('/team;id=33');
* const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
* const s: UrlSegment[] = g.segments;
* s[0].path; // returns 'team'
* s[0].parameters; // returns {id: 33}
* }
* }
* ```
*
* \@description
*
* A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
* parameters associated with the segment.
*
* \@stable
*/
var UrlSegment = (function () {
/**
* @param {?} path
* @param {?} parameters
*/
function UrlSegment(path, parameters) {
this.path = path;
this.parameters = parameters;
}
Object.defineProperty(UrlSegment.prototype, "parameterMap", {
/**
* @return {?}
*/
get: function () {
if (!this._parameterMap) {
this._parameterMap = convertToParamMap(this.parameters);
}
return this._parameterMap;
},
enumerable: true,
configurable: true
});
/**
* \@docsNotRequired
* @return {?}
*/
UrlSegment.prototype.toString = function () { return serializePath(this); };
return UrlSegment;
}());
/**
* @param {?} as
* @param {?} bs
* @return {?}
*/
function equalSegments(as, bs) {
return equalPath(as, bs) && as.every(function (a, i) { return shallowEqual(a.parameters, bs[i].parameters); });
}
/**
* @param {?} as
* @param {?} bs
* @return {?}
*/
function equalPath(as, bs) {
if (as.length !== bs.length)
return false;
return as.every(function (a, i) { return a.path === bs[i].path; });
}
/**
* @template T
* @param {?} segment
* @param {?} fn
* @return {?}
*/
function mapChildrenIntoArray(segment, fn) {
var /** @type {?} */ res = [];
forEach(segment.children, function (child, childOutlet) {
if (childOutlet === PRIMARY_OUTLET) {
res = res.concat(fn(child, childOutlet));
}
});
forEach(segment.children, function (child, childOutlet) {
if (childOutlet !== PRIMARY_OUTLET) {
res = res.concat(fn(child, childOutlet));
}
});
return res;
}
/**
* \@whatItDoes Serializes and deserializes a URL string into a URL tree.
*
* \@description The url serialization strategy is customizable. You can
* make all URLs case insensitive by providing a custom UrlSerializer.
*
* See {\@link DefaultUrlSerializer} for an example of a URL serializer.
*
* \@stable
* @abstract
*/
var UrlSerializer = (function () {
function UrlSerializer() {
}
/**
* Parse a url into a {\@link UrlTree}
* @abstract
* @param {?} url
* @return {?}
*/
UrlSerializer.prototype.parse = function (url) { };
/**
* Converts a {\@link UrlTree} into a url
* @abstract
* @param {?} tree
* @return {?}
*/
UrlSerializer.prototype.serialize = function (tree) { };
return UrlSerializer;
}());
/**
* \@whatItDoes A default implementation of the {\@link UrlSerializer}.
*
* \@description
*
* Example URLs:
*
* ```
* /inbox/33(popup:compose)
* /inbox/33;open=true/messages/44
* ```
*
* DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
* colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
* specify route specific parameters.
*
* \@stable
*/
var DefaultUrlSerializer = (function () {
function DefaultUrlSerializer() {
}
/**
* Parses a url into a {\@link UrlTree}
* @param {?} url
* @return {?}
*/
DefaultUrlSerializer.prototype.parse = function (url) {
var /** @type {?} */ p = new UrlParser(url);
return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
};
/**
* Converts a {\@link UrlTree} into a url
* @param {?} tree
* @return {?}
*/
DefaultUrlSerializer.prototype.serialize = function (tree) {
var /** @type {?} */ segment = "/" + serializeSegment(tree.root, true);
var /** @type {?} */ query = serializeQueryParams(tree.queryParams);
var /** @type {?} */ fragment = typeof tree.fragment === "string" ? "#" + encodeURI(/** @type {?} */ ((tree.fragment))) : '';
return "" + segment + query + fragment;
};
return DefaultUrlSerializer;
}());
var DEFAULT_SERIALIZER = new DefaultUrlSerializer();
/**
* @param {?} segment
* @return {?}
*/
function serializePaths(segment) {
return segment.segments.map(function (p) { return serializePath(p); }).join('/');
}
/**
* @param {?} segment
* @param {?} root
* @return {?}
*/
function serializeSegment(segment, root) {
if (!segment.hasChildren()) {
return serializePaths(segment);
}
if (root) {
var /** @type {?} */ primary = segment.children[PRIMARY_OUTLET] ?
serializeSegment(segment.children[PRIMARY_OUTLET], false) :
'';
var /** @type {?} */ children_1 = [];
forEach(segment.children, function (v, k) {
if (k !== PRIMARY_OUTLET) {
children_1.push(k + ":" + serializeSegment(v, false));
}
});
return children_1.length > 0 ? primary + "(" + children_1.join('//') + ")" : primary;
}
else {
var /** @type {?} */ children = mapChildrenIntoArray(segment, function (v, k) {
if (k === PRIMARY_OUTLET) {
return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
}
return [k + ":" + serializeSegment(v, false)];
});
return serializePaths(segment) + "/(" + children.join('//') + ")";
}
}
/**
* @param {?} s
* @return {?}
*/
function encode(s) {
return encodeURIComponent(s);
}
/**
* @param {?} s
* @return {?}
*/
function decode(s) {
return decodeURIComponent(s);
}
/**
* @param {?} path
* @return {?}
*/
function serializePath(path) {
return "" + encode(path.path) + serializeParams(path.parameters);
}
/**
* @param {?} params
* @return {?}
*/
function serializeParams(params) {
return Object.keys(params).map(function (key) { return ";" + encode(key) + "=" + encode(params[key]); }).join('');
}
/**
* @param {?} params
* @return {?}
*/
function serializeQueryParams(params) {
var /** @type {?} */ strParams = Object.keys(params).map(function (name) {
var /** @type {?} */ value = params[name];
return Array.isArray(value) ? value.map(function (v) { return encode(name) + "=" + encode(v); }).join('&') :
encode(name) + "=" + encode(value);
});
return strParams.length ? "?" + strParams.join("&") : '';
}
var SEGMENT_RE = /^[^\/()?;=&#]+/;
/**
* @param {?} str
* @return {?}
*/
function matchSegments(str) {
var /** @type {?} */ match = str.match(SEGMENT_RE);
return match ? match[0] : '';
}
var QUERY_PARAM_RE = /^[^=?&#]+/;
/**
* @param {?} str
* @return {?}
*/
function matchQueryParams(str) {
var /** @type {?} */ match = str.match(QUERY_PARAM_RE);
return match ? match[0] : '';
}
var QUERY_PARAM_VALUE_RE = /^[^?&#]+/;
/**
* @param {?} str
* @return {?}
*/
function matchUrlQueryParamValue(str) {
var /** @type {?} */ match = str.match(QUERY_PARAM_VALUE_RE);
return match ? match[0] : '';
}
var UrlParser = (function () {
/**
* @param {?} url
*/
function UrlParser(url) {
this.url = url;
this.remaining = url;
}
/**
* @return {?}
*/
UrlParser.prototype.parseRootSegment = function () {
this.consumeOptional('/');
if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
return new UrlSegmentGroup([], {});
}
// The root segment group never has segments
return new UrlSegmentGroup([], this.parseChildren());
};
/**
* @return {?}
*/
UrlParser.prototype.parseQueryParams = function () {
var /** @type {?} */ params = {};
if (this.consumeOptional('?')) {
do {
this.parseQueryParam(params);
} while (this.consumeOptional('&'));
}
return params;
};
/**
* @return {?}
*/
UrlParser.prototype.parseFragment = function () {
return this.consumeOptional('#') ? decodeURI(this.remaining) : null;
};
/**
* @return {?}
*/
UrlParser.prototype.parseChildren = function () {
if (this.remaining === '') {
return {};
}
this.consumeOptional('/');
var /** @type {?} */ segments = [];
if (!this.peekStartsWith('(')) {
segments.push(this.parseSegment());
}
while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
this.capture('/');
segments.push(this.parseSegment());
}
var /** @type {?} */ children = {};
if (this.peekStartsWith('/(')) {
this.capture('/');
children = this.parseParens(true);
}
var /** @type {?} */ res = {};
if (this.peekStartsWith('(')) {
res = this.parseParens(false);
}
if (segments.length > 0 || Object.keys(children).length > 0) {
res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
}
return res;
};
/**
* @return {?}
*/
UrlParser.prototype.parseSegment = function () {
var /** @type {?} */ path = matchSegments(this.remaining);
if (path === '' && this.peekStartsWith(';')) {
throw new Error("Empty path url segment cannot have parameters: '" + this.remaining + "'.");
}
this.capture(path);
return new UrlSegment(decode(path), this.parseMatrixParams());
};
/**
* @return {?}
*/
UrlParser.prototype.parseMatrixParams = function () {
var /** @type {?} */ params = {};
while (this.consumeOptional(';')) {
this.parseParam(params);
}
return params;
};
/**
* @param {?} params
* @return {?}
*/
UrlParser.prototype.parseParam = function (params) {
var /** @type {?} */ key = matchSegments(this.remaining);
if (!key) {
return;
}
this.capture(key);
var /** @type {?} */ value = '';
if (this.consumeOptional('=')) {
var /** @type {?} */ valueMatch = matchSegments(this.remaining);
if (valueMatch) {
value = valueMatch;
this.capture(value);
}
}
params[decode(key)] = decode(value);
};
/**
* @param {?} params
* @return {?}
*/
UrlParser.prototype.parseQueryParam = function (params) {
var /** @type {?} */ key = matchQueryParams(this.remaining);
if (!key) {
return;
}
this.capture(key);
var /** @type {?} */ value = '';
if (this.consumeOptional('=')) {
var /** @type {?} */ valueMatch = matchUrlQueryParamValue(this.remaining);
if (valueMatch) {
value = valueMatch;
this.capture(value);
}
}
var /** @type {?} */ decodedKey = decode(key);
var /** @type {?} */ decodedVal = decode(value);
if (params.hasOwnProperty(decodedKey)) {
// Append to existing values
var /** @type {?} */ currentVal = params[decodedKey];
if (!Array.isArray(currentVal)) {
currentVal = [currentVal];
params[decodedKey] = currentVal;
}
currentVal.push(decodedVal);
}
else {
// Create a new value
params[decodedKey] = decodedVal;
}
};
/**
* @param {?} allowPrimary
* @return {?}
*/
UrlParser.prototype.parseParens = function (allowPrimary) {
var /** @type {?} */ segments = {};
this.capture('(');
while (!this.consumeOptional(')') && this.remaining.length > 0) {
var /** @type {?} */ path = matchSegments(this.remaining);
var /** @type {?} */ next = this.remaining[path.length];
// if is is not one of these characters, then the segment was unescaped
// or the group was not closed
if (next !== '/' && next !== ')' && next !== ';') {
throw new Error("Cannot parse url '" + this.url + "'");
}
var /** @type {?} */ outletName = ((undefined));
if (path.indexOf(':') > -1) {
outletName = path.substr(0, path.indexOf(':'));
this.capture(outletName);
this.capture(':');
}
else if (allowPrimary) {
outletName = PRIMARY_OUTLET;
}
var /** @type {?} */ children = this.parseChildren();
segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] :
new UrlSegmentGroup([], children);
this.consumeOptional('//');
}
return segments;
};
/**
* @param {?} str
* @return {?}
*/
UrlParser.prototype.peekStartsWith = function (str) { return this.remaining.startsWith(str); };
/**
* @param {?} str
* @return {?}
*/
UrlParser.prototype.consumeOptional = function (str) {
if (this.peekStartsWith(str)) {
this.remaining = this.remaining.substring(str.length);
return true;
}
return false;
};
/**
* @param {?} str
* @return {?}
*/
UrlParser.prototype.capture = function (str) {
if (!this.consumeOptional(str)) {
throw new Error("Expected \"" + str + "\".");
}
};
return UrlParser;
}());
/**
* @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
*/
var __assign$1 = (undefined && undefined.__assign) || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var NoMatch = (function () {
/**
* @param {?=} segmentGroup
*/
function NoMatch(segmentGroup) {
this.segmentGroup = segmentGroup || null;
}
return NoMatch;
}());
var AbsoluteRedirect = (function () {
/**
* @param {?} urlTree
*/
function AbsoluteRedirect(urlTree) {
this.urlTree = urlTree;
}
return AbsoluteRedirect;
}());
/**
* @param {?} segmentGroup
* @return {?}
*/
function noMatch(segmentGroup) {
return new __WEBPACK_IMPORTED_MODULE_12_rxjs_Observable__["Observable"](function (obs) { return obs.error(new NoMatch(segmentGroup)); });
}
/**
* @param {?} newTree
* @return {?}
*/
function absoluteRedirect(newTree) {
return new __WEBPACK_IMPORTED_MODULE_12_rxjs_Observable__["Observable"](function (obs) { return obs.error(new AbsoluteRedirect(newTree)); });
}
/**
* @param {?} redirectTo
* @return {?}
*/
function namedOutletsRedirect(redirectTo) {
return new __WEBPACK_IMPORTED_MODULE_12_rxjs_Observable__["Observable"](function (obs) { return obs.error(new Error("Only absolute redirects can have named outlets. redirectTo: '" + redirectTo + "'")); });
}
/**
* @param {?} route
* @return {?}
*/
function canLoadFails(route) {
return new __WEBPACK_IMPORTED_MODULE_12_rxjs_Observable__["Observable"](function (obs) { return obs.error(navigationCancelingError("Cannot load children because the guard of the route \"path: '" + route.path + "'\" returned false")); });
}
/**
* Returns the `UrlTree` with the redirection applied.
*
* Lazy modules are loaded along the way.
* @param {?} moduleInjector
* @param {?} configLoader
* @param {?} urlSerializer
* @param {?} urlTree
* @param {?} config
* @return {?}
*/
function applyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
return new ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config).apply();
}
var ApplyRedirects = (function () {
/**
* @param {?} moduleInjector
* @param {?} configLoader
* @param {?} urlSerializer
* @param {?} urlTree
* @param {?} config
*/
function ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
this.configLoader = configLoader;
this.urlSerializer = urlSerializer;
this.urlTree = urlTree;
this.config = config;
this.allowRedirects = true;
this.ngModule = moduleInjector.get(__WEBPACK_IMPORTED_MODULE_1__angular_core__["V" /* NgModuleRef */]);
}
/**
* @return {?}
*/
ApplyRedirects.prototype.apply = function () {
var _this = this;
var /** @type {?} */ expanded$ = this.expandSegmentGroup(this.ngModule, this.config, this.urlTree.root, PRIMARY_OUTLET);
var /** @type {?} */ urlTrees$ = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(expanded$, function (rootSegmentGroup) { return _this.createUrlTree(rootSegmentGroup, _this.urlTree.queryParams, /** @type {?} */ ((_this.urlTree.fragment))); });
return __WEBPACK_IMPORTED_MODULE_13_rxjs_operator_catch__["_catch"].call(urlTrees$, function (e) {
if (e instanceof AbsoluteRedirect) {
// after an absolute redirect we do not apply any more redirects!
_this.allowRedirects = false;
// we need to run matching, so we can fetch all lazy-loaded modules
return _this.match(e.urlTree);
}
if (e instanceof NoMatch) {
throw _this.noMatchError(e);
}
throw e;
});
};
/**
* @param {?} tree
* @return {?}
*/
ApplyRedirects.prototype.match = function (tree) {
var _this = this;
var /** @type {?} */ expanded$ = this.expandSegmentGroup(this.ngModule, this.config, tree.root, PRIMARY_OUTLET);
var /** @type {?} */ mapped$ = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(expanded$, function (rootSegmentGroup) { return _this.createUrlTree(rootSegmentGroup, tree.queryParams, /** @type {?} */ ((tree.fragment))); });
return __WEBPACK_IMPORTED_MODULE_13_rxjs_operator_catch__["_catch"].call(mapped$, function (e) {
if (e instanceof NoMatch) {
throw _this.noMatchError(e);
}
throw e;
});
};
/**
* @param {?} e
* @return {?}
*/
ApplyRedirects.prototype.noMatchError = function (e) {
return new Error("Cannot match any routes. URL Segment: '" + e.segmentGroup + "'");
};
/**
* @param {?} rootCandidate
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
ApplyRedirects.prototype.createUrlTree = function (rootCandidate, queryParams, fragment) {
var /** @type {?} */ root = rootCandidate.segments.length > 0 ?
new UrlSegmentGroup([], (_a = {}, _a[PRIMARY_OUTLET] = rootCandidate, _a)) :
rootCandidate;
return new UrlTree(root, queryParams, fragment);
var _a;
};
/**
* @param {?} ngModule
* @param {?} routes
* @param {?} segmentGroup
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.expandSegmentGroup = function (ngModule, routes, segmentGroup, outlet) {
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(this.expandChildren(ngModule, routes, segmentGroup), function (children) { return new UrlSegmentGroup([], children); });
}
return this.expandSegment(ngModule, segmentGroup, routes, segmentGroup.segments, outlet, true);
};
/**
* @param {?} ngModule
* @param {?} routes
* @param {?} segmentGroup
* @return {?}
*/
ApplyRedirects.prototype.expandChildren = function (ngModule, routes, segmentGroup) {
var _this = this;
return waitForMap(segmentGroup.children, function (childOutlet, child) { return _this.expandSegmentGroup(ngModule, routes, child, childOutlet); });
};
/**
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} segments
* @param {?} outlet
* @param {?} allowRedirects
* @return {?}
*/
ApplyRedirects.prototype.expandSegment = function (ngModule, segmentGroup, routes, segments, outlet, allowRedirects) {
var _this = this;
var /** @type {?} */ routes$ = __WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"].apply(void 0, routes);
var /** @type {?} */ processedRoutes$ = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(routes$, function (r) {
var /** @type {?} */ expanded$ = _this.expandSegmentAgainstRoute(ngModule, segmentGroup, routes, r, segments, outlet, allowRedirects);
return __WEBPACK_IMPORTED_MODULE_13_rxjs_operator_catch__["_catch"].call(expanded$, function (e) {
if (e instanceof NoMatch) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(null);
}
throw e;
});
});
var /** @type {?} */ concattedProcessedRoutes$ = __WEBPACK_IMPORTED_MODULE_14_rxjs_operator_concatAll__["concatAll"].call(processedRoutes$);
var /** @type {?} */ first$ = __WEBPACK_IMPORTED_MODULE_8_rxjs_operator_first__["first"].call(concattedProcessedRoutes$, function (s) { return !!s; });
return __WEBPACK_IMPORTED_MODULE_13_rxjs_operator_catch__["_catch"].call(first$, function (e, _) {
if (e instanceof __WEBPACK_IMPORTED_MODULE_15_rxjs_util_EmptyError__["EmptyError"]) {
if (_this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(new UrlSegmentGroup([], {}));
}
throw new NoMatch(segmentGroup);
}
throw e;
});
};
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) {
return segments.length === 0 && !segmentGroup.children[outlet];
};
/**
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} paths
* @param {?} outlet
* @param {?} allowRedirects
* @return {?}
*/
ApplyRedirects.prototype.expandSegmentAgainstRoute = function (ngModule, segmentGroup, routes, route, paths, outlet, allowRedirects) {
if (getOutlet$1(route) !== outlet) {
return noMatch(segmentGroup);
}
if (route.redirectTo === undefined) {
return this.matchSegmentAgainstRoute(ngModule, segmentGroup, route, paths);
}
if (allowRedirects && this.allowRedirects) {
return this.expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, paths, outlet);
}
return noMatch(segmentGroup);
};
/**
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.expandSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) {
if (route.path === '**') {
return this.expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet);
}
return this.expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet);
};
/**
* @param {?} ngModule
* @param {?} routes
* @param {?} route
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.expandWildCardWithParamsAgainstRouteUsingRedirect = function (ngModule, routes, route, outlet) {
var _this = this;
var /** @type {?} */ newTree = this.applyRedirectCommands([], /** @type {?} */ ((route.redirectTo)), {});
if (((route.redirectTo)).startsWith('/')) {
return absoluteRedirect(newTree);
}
return __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(this.lineralizeSegments(route, newTree), function (newSegments) {
var /** @type {?} */ group = new UrlSegmentGroup(newSegments, {});
return _this.expandSegment(ngModule, group, routes, newSegments, outlet, false);
});
};
/**
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.expandRegularSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) {
var _this = this;
var _a = match(segmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild, positionalParamSegments = _a.positionalParamSegments;
if (!matched)
return noMatch(segmentGroup);
var /** @type {?} */ newTree = this.applyRedirectCommands(consumedSegments, /** @type {?} */ ((route.redirectTo)), /** @type {?} */ (positionalParamSegments));
if (((route.redirectTo)).startsWith('/')) {
return absoluteRedirect(newTree);
}
return __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(this.lineralizeSegments(route, newTree), function (newSegments) {
return _this.expandSegment(ngModule, segmentGroup, routes, newSegments.concat(segments.slice(lastChild)), outlet, false);
});
};
/**
* @param {?} ngModule
* @param {?} rawSegmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
ApplyRedirects.prototype.matchSegmentAgainstRoute = function (ngModule, rawSegmentGroup, route, segments) {
var _this = this;
if (route.path === '**') {
if (route.loadChildren) {
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(this.configLoader.load(ngModule.injector, route), function (cfg) {
route._loadedConfig = cfg;
return new UrlSegmentGroup(segments, {});
});
}
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(new UrlSegmentGroup(segments, {}));
}
var _a = match(rawSegmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild;
if (!matched)
return noMatch(rawSegmentGroup);
var /** @type {?} */ rawSlicedSegments = segments.slice(lastChild);
var /** @type {?} */ childConfig$ = this.getChildConfig(ngModule, route);
return __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(childConfig$, function (routerConfig) {
var /** @type {?} */ childModule = routerConfig.module;
var /** @type {?} */ childConfig = routerConfig.routes;
var _a = split(rawSegmentGroup, consumedSegments, rawSlicedSegments, childConfig), segmentGroup = _a.segmentGroup, slicedSegments = _a.slicedSegments;
if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
var /** @type {?} */ expanded$_1 = _this.expandChildren(childModule, childConfig, segmentGroup);
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(expanded$_1, function (children) { return new UrlSegmentGroup(consumedSegments, children); });
}
if (childConfig.length === 0 && slicedSegments.length === 0) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(new UrlSegmentGroup(consumedSegments, {}));
}
var /** @type {?} */ expanded$ = _this.expandSegment(childModule, segmentGroup, childConfig, slicedSegments, PRIMARY_OUTLET, true);
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(expanded$, function (cs) { return new UrlSegmentGroup(consumedSegments.concat(cs.segments), cs.children); });
});
};
/**
* @param {?} ngModule
* @param {?} route
* @return {?}
*/
ApplyRedirects.prototype.getChildConfig = function (ngModule, route) {
var _this = this;
if (route.children) {
// The children belong to the same module
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(new LoadedRouterConfig(route.children, ngModule));
}
if (route.loadChildren) {
// lazy children belong to the loaded module
if (route._loadedConfig !== undefined) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(route._loadedConfig);
}
return __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(runCanLoadGuard(ngModule.injector, route), function (shouldLoad) {
if (shouldLoad) {
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(_this.configLoader.load(ngModule.injector, route), function (cfg) {
route._loadedConfig = cfg;
return cfg;
});
}
return canLoadFails(route);
});
}
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(new LoadedRouterConfig([], ngModule));
};
/**
* @param {?} route
* @param {?} urlTree
* @return {?}
*/
ApplyRedirects.prototype.lineralizeSegments = function (route, urlTree) {
var /** @type {?} */ res = [];
var /** @type {?} */ c = urlTree.root;
while (true) {
res = res.concat(c.segments);
if (c.numberOfChildren === 0) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(res);
}
if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
return namedOutletsRedirect(/** @type {?} */ ((route.redirectTo)));
}
c = c.children[PRIMARY_OUTLET];
}
};
/**
* @param {?} segments
* @param {?} redirectTo
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.applyRedirectCommands = function (segments, redirectTo, posParams) {
return this.applyRedirectCreatreUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
};
/**
* @param {?} redirectTo
* @param {?} urlTree
* @param {?} segments
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.applyRedirectCreatreUrlTree = function (redirectTo, urlTree, segments, posParams) {
var /** @type {?} */ newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);
};
/**
* @param {?} redirectToParams
* @param {?} actualParams
* @return {?}
*/
ApplyRedirects.prototype.createQueryParams = function (redirectToParams, actualParams) {
var /** @type {?} */ res = {};
forEach(redirectToParams, function (v, k) {
res[k] = v.startsWith(':') ? actualParams[v.substring(1)] : v;
});
return res;
};
/**
* @param {?} redirectTo
* @param {?} group
* @param {?} segments
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.createSegmentGroup = function (redirectTo, group, segments, posParams) {
var _this = this;
var /** @type {?} */ updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
var /** @type {?} */ children = {};
forEach(group.children, function (child, name) {
children[name] = _this.createSegmentGroup(redirectTo, child, segments, posParams);
});
return new UrlSegmentGroup(updatedSegments, children);
};
/**
* @param {?} redirectTo
* @param {?} redirectToSegments
* @param {?} actualSegments
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.createSegments = function (redirectTo, redirectToSegments, actualSegments, posParams) {
var _this = this;
return redirectToSegments.map(function (s) { return s.path.startsWith(':') ? _this.findPosParam(redirectTo, s, posParams) :
_this.findOrReturn(s, actualSegments); });
};
/**
* @param {?} redirectTo
* @param {?} redirectToUrlSegment
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.findPosParam = function (redirectTo, redirectToUrlSegment, posParams) {
var /** @type {?} */ pos = posParams[redirectToUrlSegment.path.substring(1)];
if (!pos)
throw new Error("Cannot redirect to '" + redirectTo + "'. Cannot find '" + redirectToUrlSegment.path + "'.");
return pos;
};
/**
* @param {?} redirectToUrlSegment
* @param {?} actualSegments
* @return {?}
*/
ApplyRedirects.prototype.findOrReturn = function (redirectToUrlSegment, actualSegments) {
var /** @type {?} */ idx = 0;
for (var _i = 0, actualSegments_1 = actualSegments; _i < actualSegments_1.length; _i++) {
var s = actualSegments_1[_i];
if (s.path === redirectToUrlSegment.path) {
actualSegments.splice(idx);
return s;
}
idx++;
}
return redirectToUrlSegment;
};
return ApplyRedirects;
}());
/**
* @param {?} moduleInjector
* @param {?} route
* @return {?}
*/
function runCanLoadGuard(moduleInjector, route) {
var /** @type {?} */ canLoad = route.canLoad;
if (!canLoad || canLoad.length === 0)
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(true);
var /** @type {?} */ obs = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(canLoad), function (injectionToken) {
var /** @type {?} */ guard = moduleInjector.get(injectionToken);
return wrapIntoObservable(guard.canLoad ? guard.canLoad(route) : guard(route));
});
return andObservables(obs);
}
/**
* @param {?} segmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
function match(segmentGroup, route, segments) {
if (route.path === '') {
if ((route.pathMatch === 'full') && (segmentGroup.hasChildren() || segments.length > 0)) {
return { matched: false, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
}
return { matched: true, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
}
var /** @type {?} */ matcher = route.matcher || defaultUrlMatcher;
var /** @type {?} */ res = matcher(segments, segmentGroup, route);
if (!res) {
return {
matched: false, consumedSegments: /** @type {?} */ ([]), lastChild: 0, positionalParamSegments: {},
};
}
return {
matched: true,
consumedSegments: /** @type {?} */ ((res.consumed)),
lastChild: /** @type {?} */ ((res.consumed.length)),
positionalParamSegments: /** @type {?} */ ((res.posParams)),
};
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} slicedSegments
* @param {?} config
* @return {?}
*/
function split(segmentGroup, consumedSegments, slicedSegments, config) {
if (slicedSegments.length > 0 &&
containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, slicedSegments, config)) {
var /** @type {?} */ s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptySegments(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
return { segmentGroup: mergeTrivialChildren(s), slicedSegments: [] };
}
if (slicedSegments.length === 0 &&
containsEmptyPathRedirects(segmentGroup, slicedSegments, config)) {
var /** @type {?} */ s = new UrlSegmentGroup(segmentGroup.segments, addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
return { segmentGroup: mergeTrivialChildren(s), slicedSegments: slicedSegments };
}
return { segmentGroup: segmentGroup, slicedSegments: slicedSegments };
}
/**
* @param {?} s
* @return {?}
*/
function mergeTrivialChildren(s) {
if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
var /** @type {?} */ c = s.children[PRIMARY_OUTLET];
return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
}
return s;
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @param {?} children
* @return {?}
*/
function addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
var /** @type {?} */ res = {};
for (var _i = 0, routes_1 = routes; _i < routes_1.length; _i++) {
var r = routes_1[_i];
if (isEmptyPathRedirect(segmentGroup, slicedSegments, r) && !children[getOutlet$1(r)]) {
res[getOutlet$1(r)] = new UrlSegmentGroup([], {});
}
}
return __assign$1({}, children, res);
}
/**
* @param {?} routes
* @param {?} primarySegmentGroup
* @return {?}
*/
function createChildrenForEmptySegments(routes, primarySegmentGroup) {
var /** @type {?} */ res = {};
res[PRIMARY_OUTLET] = primarySegmentGroup;
for (var _i = 0, routes_2 = routes; _i < routes_2.length; _i++) {
var r = routes_2[_i];
if (r.path === '' && getOutlet$1(r) !== PRIMARY_OUTLET) {
res[getOutlet$1(r)] = new UrlSegmentGroup([], {});
}
}
return res;
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, segments, routes) {
return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r) && getOutlet$1(r) !== PRIMARY_OUTLET; });
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathRedirects(segmentGroup, segments, routes) {
return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r); });
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} r
* @return {?}
*/
function isEmptyPathRedirect(segmentGroup, segments, r) {
if ((segmentGroup.hasChildren() || segments.length > 0) && r.pathMatch === 'full') {
return false;
}
return r.path === '' && r.redirectTo !== undefined;
}
/**
* @param {?} route
* @return {?}
*/
function getOutlet$1(route) {
return route.outlet || PRIMARY_OUTLET;
}
/**
* @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
*/
var Tree = (function () {
/**
* @param {?} root
*/
function Tree(root) {
this._root = root;
}
Object.defineProperty(Tree.prototype, "root", {
/**
* @return {?}
*/
get: function () { return this._root.value; },
enumerable: true,
configurable: true
});
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.parent = function (t) {
var /** @type {?} */ p = this.pathFromRoot(t);
return p.length > 1 ? p[p.length - 2] : null;
};
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.children = function (t) {
var /** @type {?} */ n = findNode(t, this._root);
return n ? n.children.map(function (t) { return t.value; }) : [];
};
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.firstChild = function (t) {
var /** @type {?} */ n = findNode(t, this._root);
return n && n.children.length > 0 ? n.children[0].value : null;
};
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.siblings = function (t) {
var /** @type {?} */ p = findPath(t, this._root, []);
if (p.length < 2)
return [];
var /** @type {?} */ c = p[p.length - 2].children.map(function (c) { return c.value; });
return c.filter(function (cc) { return cc !== t; });
};
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.pathFromRoot = function (t) { return findPath(t, this._root, []).map(function (s) { return s.value; }); };
return Tree;
}());
/**
* @template T
* @param {?} expected
* @param {?} c
* @return {?}
*/
function findNode(expected, c) {
if (expected === c.value)
return c;
for (var _i = 0, _a = c.children; _i < _a.length; _i++) {
var cc = _a[_i];
var /** @type {?} */ r = findNode(expected, cc);
if (r)
return r;
}
return null;
}
/**
* @template T
* @param {?} expected
* @param {?} c
* @param {?} collected
* @return {?}
*/
function findPath(expected, c, collected) {
collected.push(c);
if (expected === c.value)
return collected;
for (var _i = 0, _a = c.children; _i < _a.length; _i++) {
var cc = _a[_i];
var /** @type {?} */ cloned = collected.slice(0);
var /** @type {?} */ r = findPath(expected, cc, cloned);
if (r.length > 0)
return r;
}
return [];
}
var TreeNode = (function () {
/**
* @param {?} value
* @param {?} children
*/
function TreeNode(value, children) {
this.value = value;
this.children = children;
}
/**
* @return {?}
*/
TreeNode.prototype.toString = function () { return "TreeNode(" + this.value + ")"; };
return TreeNode;
}());
/**
* @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
*/
var __assign$2 = (undefined && undefined.__assign) || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
/**
* \@whatItDoes Represents the state of the router.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const state: RouterState = router.routerState;
* const root: ActivatedRoute = state.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
* }
* }
* ```
*
* \@description
* RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL
* segments, the extracted parameters, and the resolved data.
*
* See {\@link ActivatedRoute} for more information.
*
* \@stable
*/
var RouterState = (function (_super) {
__extends(RouterState, _super);
/**
* \@internal
* @param {?} root
* @param {?} snapshot
*/
function RouterState(root, snapshot) {
var _this = _super.call(this, root) || this;
_this.snapshot = snapshot;
setRouterStateSnapshot(_this, root);
return _this;
}
/**
* @return {?}
*/
RouterState.prototype.toString = function () { return this.snapshot.toString(); };
return RouterState;
}(Tree));
/**
* @param {?} urlTree
* @param {?} rootComponent
* @return {?}
*/
function createEmptyState(urlTree, rootComponent) {
var /** @type {?} */ snapshot = createEmptyStateSnapshot(urlTree, rootComponent);
var /** @type {?} */ emptyUrl = new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"]([new UrlSegment('', {})]);
var /** @type {?} */ emptyParams = new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"]({});
var /** @type {?} */ emptyData = new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"]({});
var /** @type {?} */ emptyQueryParams = new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"]({});
var /** @type {?} */ fragment = new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"]('');
var /** @type {?} */ activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);
activated.snapshot = snapshot.root;
return new RouterState(new TreeNode(activated, []), snapshot);
}
/**
* @param {?} urlTree
* @param {?} rootComponent
* @return {?}
*/
function createEmptyStateSnapshot(urlTree, rootComponent) {
var /** @type {?} */ emptyParams = {};
var /** @type {?} */ emptyData = {};
var /** @type {?} */ emptyQueryParams = {};
var /** @type {?} */ fragment = '';
var /** @type {?} */ activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, urlTree.root, -1, {});
return new RouterStateSnapshot('', new TreeNode(activated, []));
}
/**
* \@whatItDoes Contains the information about a route associated with a component loaded in an
* outlet.
* An `ActivatedRoute` can also be used to traverse the router state tree.
*
* \@howToUse
*
* ```
* \@Component({...})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: Observable<string> = route.params.map(p => p.id);
* const url: Observable<string> = route.url.map(segments => segments.join(''));
* // route.data includes both `data` and `resolve`
* const user = route.data.map(d => d.user);
* }
* }
* ```
*
* \@stable
*/
var ActivatedRoute = (function () {
/**
* \@internal
* @param {?} url
* @param {?} params
* @param {?} queryParams
* @param {?} fragment
* @param {?} data
* @param {?} outlet
* @param {?} component
* @param {?} futureSnapshot
*/
function ActivatedRoute(url, params, queryParams, fragment, data, outlet, component, futureSnapshot) {
this.url = url;
this.params = params;
this.queryParams = queryParams;
this.fragment = fragment;
this.data = data;
this.outlet = outlet;
this.component = component;
this._futureSnapshot = futureSnapshot;
}
Object.defineProperty(ActivatedRoute.prototype, "routeConfig", {
/**
* The configuration used to match this route
* @return {?}
*/
get: function () { return this._futureSnapshot.routeConfig; },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "root", {
/**
* The root of the router state
* @return {?}
*/
get: function () { return this._routerState.root; },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "parent", {
/**
* The parent of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.parent(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "firstChild", {
/**
* The first child of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.firstChild(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "children", {
/**
* The children of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.children(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "pathFromRoot", {
/**
* The path from the root of the router state tree to this route
* @return {?}
*/
get: function () { return this._routerState.pathFromRoot(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "paramMap", {
/**
* @return {?}
*/
get: function () {
if (!this._paramMap) {
this._paramMap = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(this.params, function (p) { return convertToParamMap(p); });
}
return this._paramMap;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "queryParamMap", {
/**
* @return {?}
*/
get: function () {
if (!this._queryParamMap) {
this._queryParamMap =
__WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(this.queryParams, function (p) { return convertToParamMap(p); });
}
return this._queryParamMap;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
ActivatedRoute.prototype.toString = function () {
return this.snapshot ? this.snapshot.toString() : "Future(" + this._futureSnapshot + ")";
};
return ActivatedRoute;
}());
/**
* \@internal
* @param {?} route
* @return {?}
*/
function inheritedParamsDataResolve(route) {
var /** @type {?} */ pathToRoot = route.pathFromRoot;
var /** @type {?} */ inhertingStartingFrom = pathToRoot.length - 1;
while (inhertingStartingFrom >= 1) {
var /** @type {?} */ current = pathToRoot[inhertingStartingFrom];
var /** @type {?} */ parent = pathToRoot[inhertingStartingFrom - 1];
// current route is an empty path => inherits its parent's params and data
if (current.routeConfig && current.routeConfig.path === '') {
inhertingStartingFrom--;
}
else if (!parent.component) {
inhertingStartingFrom--;
}
else {
break;
}
}
return pathToRoot.slice(inhertingStartingFrom).reduce(function (res, curr) {
var /** @type {?} */ params = __assign$2({}, res.params, curr.params);
var /** @type {?} */ data = __assign$2({}, res.data, curr.data);
var /** @type {?} */ resolve = __assign$2({}, res.resolve, curr._resolvedData);
return { params: params, data: data, resolve: resolve };
}, /** @type {?} */ ({ params: {}, data: {}, resolve: {} }));
}
/**
* \@whatItDoes Contains the information about a route associated with a component loaded in an
* outlet
* at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router
* state tree.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'./my-component.html'})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: string = route.snapshot.params.id;
* const url: string = route.snapshot.url.join('');
* const user = route.snapshot.data.user;
* }
* }
* ```
*
* \@stable
*/
var ActivatedRouteSnapshot = (function () {
/**
* \@internal
* @param {?} url
* @param {?} params
* @param {?} queryParams
* @param {?} fragment
* @param {?} data
* @param {?} outlet
* @param {?} component
* @param {?} routeConfig
* @param {?} urlSegment
* @param {?} lastPathIndex
* @param {?} resolve
*/
function ActivatedRouteSnapshot(url, params, queryParams, fragment, data, outlet, component, routeConfig, urlSegment, lastPathIndex, resolve) {
this.url = url;
this.params = params;
this.queryParams = queryParams;
this.fragment = fragment;
this.data = data;
this.outlet = outlet;
this.component = component;
this._routeConfig = routeConfig;
this._urlSegment = urlSegment;
this._lastPathIndex = lastPathIndex;
this._resolve = resolve;
}
Object.defineProperty(ActivatedRouteSnapshot.prototype, "routeConfig", {
/**
* The configuration used to match this route
* @return {?}
*/
get: function () { return this._routeConfig; },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "root", {
/**
* The root of the router state
* @return {?}
*/
get: function () { return this._routerState.root; },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "parent", {
/**
* The parent of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.parent(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "firstChild", {
/**
* The first child of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.firstChild(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "children", {
/**
* The children of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.children(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "pathFromRoot", {
/**
* The path from the root of the router state tree to this route
* @return {?}
*/
get: function () { return this._routerState.pathFromRoot(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "paramMap", {
/**
* @return {?}
*/
get: function () {
if (!this._paramMap) {
this._paramMap = convertToParamMap(this.params);
}
return this._paramMap;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "queryParamMap", {
/**
* @return {?}
*/
get: function () {
if (!this._queryParamMap) {
this._queryParamMap = convertToParamMap(this.queryParams);
}
return this._queryParamMap;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
ActivatedRouteSnapshot.prototype.toString = function () {
var /** @type {?} */ url = this.url.map(function (segment) { return segment.toString(); }).join('/');
var /** @type {?} */ matched = this._routeConfig ? this._routeConfig.path : '';
return "Route(url:'" + url + "', path:'" + matched + "')";
};
return ActivatedRouteSnapshot;
}());
/**
* \@whatItDoes Represents the state of the router at a moment in time.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const state: RouterState = router.routerState;
* const snapshot: RouterStateSnapshot = state.snapshot;
* const root: ActivatedRouteSnapshot = snapshot.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
* }
* }
* ```
*
* \@description
* RouterStateSnapshot is a tree of activated route snapshots. Every node in this tree knows about
* the "consumed" URL segments, the extracted parameters, and the resolved data.
*
* \@stable
*/
var RouterStateSnapshot = (function (_super) {
__extends(RouterStateSnapshot, _super);
/**
* \@internal
* @param {?} url
* @param {?} root
*/
function RouterStateSnapshot(url, root) {
var _this = _super.call(this, root) || this;
_this.url = url;
setRouterStateSnapshot(_this, root);
return _this;
}
/**
* @return {?}
*/
RouterStateSnapshot.prototype.toString = function () { return serializeNode(this._root); };
return RouterStateSnapshot;
}(Tree));
/**
* @template U, T
* @param {?} state
* @param {?} node
* @return {?}
*/
function setRouterStateSnapshot(state, node) {
node.value._routerState = state;
node.children.forEach(function (c) { return setRouterStateSnapshot(state, c); });
}
/**
* @param {?} node
* @return {?}
*/
function serializeNode(node) {
var /** @type {?} */ c = node.children.length > 0 ? " { " + node.children.map(serializeNode).join(", ") + " } " : '';
return "" + node.value + c;
}
/**
* The expectation is that the activate route is created with the right set of parameters.
* So we push new values into the observables only when they are not the initial values.
* And we detect that by checking if the snapshot field is set.
* @param {?} route
* @return {?}
*/
function advanceActivatedRoute(route) {
if (route.snapshot) {
var /** @type {?} */ currentSnapshot = route.snapshot;
route.snapshot = route._futureSnapshot;
if (!shallowEqual(currentSnapshot.queryParams, route._futureSnapshot.queryParams)) {
((route.queryParams)).next(route._futureSnapshot.queryParams);
}
if (currentSnapshot.fragment !== route._futureSnapshot.fragment) {
((route.fragment)).next(route._futureSnapshot.fragment);
}
if (!shallowEqual(currentSnapshot.params, route._futureSnapshot.params)) {
((route.params)).next(route._futureSnapshot.params);
}
if (!shallowEqualArrays(currentSnapshot.url, route._futureSnapshot.url)) {
((route.url)).next(route._futureSnapshot.url);
}
if (!shallowEqual(currentSnapshot.data, route._futureSnapshot.data)) {
((route.data)).next(route._futureSnapshot.data);
}
}
else {
route.snapshot = route._futureSnapshot;
// this is for resolved data
((route.data)).next(route._futureSnapshot.data);
}
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function equalParamsAndUrlSegments(a, b) {
var /** @type {?} */ equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
var /** @type {?} */ parentsMismatch = !a.parent !== !b.parent;
return equalUrlParams && !parentsMismatch &&
(!a.parent || equalParamsAndUrlSegments(a.parent, /** @type {?} */ ((b.parent))));
}
/**
* @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
*/
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?} prevState
* @return {?}
*/
function createRouterState(routeReuseStrategy, curr, prevState) {
var /** @type {?} */ root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
return new RouterState(root, curr);
}
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?=} prevState
* @return {?}
*/
function createNode(routeReuseStrategy, curr, prevState) {
// reuse an activated route that is currently displayed on the screen
if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
var /** @type {?} */ value = prevState.value;
value._futureSnapshot = curr.value;
var /** @type {?} */ children = createOrReuseChildren(routeReuseStrategy, curr, prevState);
return new TreeNode(value, children);
}
else if (routeReuseStrategy.retrieve(curr.value)) {
var /** @type {?} */ tree_1 = ((routeReuseStrategy.retrieve(curr.value))).route;
setFutureSnapshotsOfActivatedRoutes(curr, tree_1);
return tree_1;
}
else {
var /** @type {?} */ value = createActivatedRoute(curr.value);
var /** @type {?} */ children = curr.children.map(function (c) { return createNode(routeReuseStrategy, c); });
return new TreeNode(value, children);
}
}
/**
* @param {?} curr
* @param {?} result
* @return {?}
*/
function setFutureSnapshotsOfActivatedRoutes(curr, result) {
if (curr.value.routeConfig !== result.value.routeConfig) {
throw new Error('Cannot reattach ActivatedRouteSnapshot created from a different route');
}
if (curr.children.length !== result.children.length) {
throw new Error('Cannot reattach ActivatedRouteSnapshot with a different number of children');
}
result.value._futureSnapshot = curr.value;
for (var /** @type {?} */ i = 0; i < curr.children.length; ++i) {
setFutureSnapshotsOfActivatedRoutes(curr.children[i], result.children[i]);
}
}
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?} prevState
* @return {?}
*/
function createOrReuseChildren(routeReuseStrategy, curr, prevState) {
return curr.children.map(function (child) {
for (var _i = 0, _a = prevState.children; _i < _a.length; _i++) {
var p = _a[_i];
if (routeReuseStrategy.shouldReuseRoute(p.value.snapshot, child.value)) {
return createNode(routeReuseStrategy, child, p);
}
}
return createNode(routeReuseStrategy, child);
});
}
/**
* @param {?} c
* @return {?}
*/
function createActivatedRoute(c) {
return new ActivatedRoute(new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"](c.url), new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"](c.params), new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"](c.queryParams), new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"](c.fragment), new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"](c.data), c.outlet, c.component, c);
}
/**
* @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
*/
/**
* @param {?} route
* @param {?} urlTree
* @param {?} commands
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
function createUrlTree(route, urlTree, commands, queryParams, fragment) {
if (commands.length === 0) {
return tree(urlTree.root, urlTree.root, urlTree, queryParams, fragment);
}
var /** @type {?} */ nav = computeNavigation(commands);
if (nav.toRoot()) {
return tree(urlTree.root, new UrlSegmentGroup([], {}), urlTree, queryParams, fragment);
}
var /** @type {?} */ startingPosition = findStartingPosition(nav, urlTree, route);
var /** @type {?} */ segmentGroup = startingPosition.processChildren ?
updateSegmentGroupChildren(startingPosition.segmentGroup, startingPosition.index, nav.commands) :
updateSegmentGroup(startingPosition.segmentGroup, startingPosition.index, nav.commands);
return tree(startingPosition.segmentGroup, segmentGroup, urlTree, queryParams, fragment);
}
/**
* @param {?} command
* @return {?}
*/
function isMatrixParams(command) {
return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;
}
/**
* @param {?} oldSegmentGroup
* @param {?} newSegmentGroup
* @param {?} urlTree
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
function tree(oldSegmentGroup, newSegmentGroup, urlTree, queryParams, fragment) {
var /** @type {?} */ qp = {};
if (queryParams) {
forEach(queryParams, function (value, name) {
qp[name] = Array.isArray(value) ? value.map(function (v) { return "" + v; }) : "" + value;
});
}
if (urlTree.root === oldSegmentGroup) {
return new UrlTree(newSegmentGroup, qp, fragment);
}
return new UrlTree(replaceSegment(urlTree.root, oldSegmentGroup, newSegmentGroup), qp, fragment);
}
/**
* @param {?} current
* @param {?} oldSegment
* @param {?} newSegment
* @return {?}
*/
function replaceSegment(current, oldSegment, newSegment) {
var /** @type {?} */ children = {};
forEach(current.children, function (c, outletName) {
if (c === oldSegment) {
children[outletName] = newSegment;
}
else {
children[outletName] = replaceSegment(c, oldSegment, newSegment);
}
});
return new UrlSegmentGroup(current.segments, children);
}
var Navigation = (function () {
/**
* @param {?} isAbsolute
* @param {?} numberOfDoubleDots
* @param {?} commands
*/
function Navigation(isAbsolute, numberOfDoubleDots, commands) {
this.isAbsolute = isAbsolute;
this.numberOfDoubleDots = numberOfDoubleDots;
this.commands = commands;
if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
throw new Error('Root segment cannot have matrix parameters');
}
var cmdWithOutlet = commands.find(function (c) { return typeof c === 'object' && c != null && c.outlets; });
if (cmdWithOutlet && cmdWithOutlet !== last$1(commands)) {
throw new Error('{outlets:{}} has to be the last command');
}
}
/**
* @return {?}
*/
Navigation.prototype.toRoot = function () {
return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';
};
return Navigation;
}());
/**
* Transforms commands to a normalized `Navigation`
* @param {?} commands
* @return {?}
*/
function computeNavigation(commands) {
if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') {
return new Navigation(true, 0, commands);
}
var /** @type {?} */ numberOfDoubleDots = 0;
var /** @type {?} */ isAbsolute = false;
var /** @type {?} */ res = commands.reduce(function (res, cmd, cmdIdx) {
if (typeof cmd === 'object' && cmd != null) {
if (cmd.outlets) {
var /** @type {?} */ outlets_1 = {};
forEach(cmd.outlets, function (commands, name) {
outlets_1[name] = typeof commands === 'string' ? commands.split('/') : commands;
});
return res.concat([{ outlets: outlets_1 }]);
}
if (cmd.segmentPath) {
return res.concat([cmd.segmentPath]);
}
}
if (!(typeof cmd === 'string')) {
return res.concat([cmd]);
}
if (cmdIdx === 0) {
cmd.split('/').forEach(function (urlPart, partIndex) {
if (partIndex == 0 && urlPart === '.') {
}
else if (partIndex == 0 && urlPart === '') {
isAbsolute = true;
}
else if (urlPart === '..') {
numberOfDoubleDots++;
}
else if (urlPart != '') {
res.push(urlPart);
}
});
return res;
}
return res.concat([cmd]);
}, []);
return new Navigation(isAbsolute, numberOfDoubleDots, res);
}
var Position = (function () {
/**
* @param {?} segmentGroup
* @param {?} processChildren
* @param {?} index
*/
function Position(segmentGroup, processChildren, index) {
this.segmentGroup = segmentGroup;
this.processChildren = processChildren;
this.index = index;
}
return Position;
}());
/**
* @param {?} nav
* @param {?} tree
* @param {?} route
* @return {?}
*/
function findStartingPosition(nav, tree, route) {
if (nav.isAbsolute) {
return new Position(tree.root, true, 0);
}
if (route.snapshot._lastPathIndex === -1) {
return new Position(route.snapshot._urlSegment, true, 0);
}
var /** @type {?} */ modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;
var /** @type {?} */ index = route.snapshot._lastPathIndex + modifier;
return createPositionApplyingDoubleDots(route.snapshot._urlSegment, index, nav.numberOfDoubleDots);
}
/**
* @param {?} group
* @param {?} index
* @param {?} numberOfDoubleDots
* @return {?}
*/
function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {
var /** @type {?} */ g = group;
var /** @type {?} */ ci = index;
var /** @type {?} */ dd = numberOfDoubleDots;
while (dd > ci) {
dd -= ci;
g = ((g.parent));
if (!g) {
throw new Error('Invalid number of \'../\'');
}
ci = g.segments.length;
}
return new Position(g, false, ci - dd);
}
/**
* @param {?} command
* @return {?}
*/
function getPath(command) {
if (typeof command === 'object' && command != null && command.outlets) {
return command.outlets[PRIMARY_OUTLET];
}
return "" + command;
}
/**
* @param {?} commands
* @return {?}
*/
function getOutlets(commands) {
if (!(typeof commands[0] === 'object'))
return _a = {}, _a[PRIMARY_OUTLET] = commands, _a;
if (commands[0].outlets === undefined)
return _b = {}, _b[PRIMARY_OUTLET] = commands, _b;
return commands[0].outlets;
var _a, _b;
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function updateSegmentGroup(segmentGroup, startIndex, commands) {
if (!segmentGroup) {
segmentGroup = new UrlSegmentGroup([], {});
}
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
}
var /** @type {?} */ m = prefixedWith(segmentGroup, startIndex, commands);
var /** @type {?} */ slicedCommands = commands.slice(m.commandIndex);
if (m.match && m.pathIndex < segmentGroup.segments.length) {
var /** @type {?} */ g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
g.children[PRIMARY_OUTLET] =
new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
return updateSegmentGroupChildren(g, 0, slicedCommands);
}
else if (m.match && slicedCommands.length === 0) {
return new UrlSegmentGroup(segmentGroup.segments, {});
}
else if (m.match && !segmentGroup.hasChildren()) {
return createNewSegmentGroup(segmentGroup, startIndex, commands);
}
else if (m.match) {
return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);
}
else {
return createNewSegmentGroup(segmentGroup, startIndex, commands);
}
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function updateSegmentGroupChildren(segmentGroup, startIndex, commands) {
if (commands.length === 0) {
return new UrlSegmentGroup(segmentGroup.segments, {});
}
else {
var /** @type {?} */ outlets_2 = getOutlets(commands);
var /** @type {?} */ children_2 = {};
forEach(outlets_2, function (commands, outlet) {
if (commands !== null) {
children_2[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);
}
});
forEach(segmentGroup.children, function (child, childOutlet) {
if (outlets_2[childOutlet] === undefined) {
children_2[childOutlet] = child;
}
});
return new UrlSegmentGroup(segmentGroup.segments, children_2);
}
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function prefixedWith(segmentGroup, startIndex, commands) {
var /** @type {?} */ currentCommandIndex = 0;
var /** @type {?} */ currentPathIndex = startIndex;
var /** @type {?} */ noMatch = { match: false, pathIndex: 0, commandIndex: 0 };
while (currentPathIndex < segmentGroup.segments.length) {
if (currentCommandIndex >= commands.length)
return noMatch;
var /** @type {?} */ path = segmentGroup.segments[currentPathIndex];
var /** @type {?} */ curr = getPath(commands[currentCommandIndex]);
var /** @type {?} */ next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
if (currentPathIndex > 0 && curr === undefined)
break;
if (curr && next && (typeof next === 'object') && next.outlets === undefined) {
if (!compare(curr, next, path))
return noMatch;
currentCommandIndex += 2;
}
else {
if (!compare(curr, {}, path))
return noMatch;
currentCommandIndex++;
}
currentPathIndex++;
}
return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex };
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function createNewSegmentGroup(segmentGroup, startIndex, commands) {
var /** @type {?} */ paths = segmentGroup.segments.slice(0, startIndex);
var /** @type {?} */ i = 0;
while (i < commands.length) {
if (typeof commands[i] === 'object' && commands[i].outlets !== undefined) {
var /** @type {?} */ children = createNewSegmentChildren(commands[i].outlets);
return new UrlSegmentGroup(paths, children);
}
// if we start with an object literal, we need to reuse the path part from the segment
if (i === 0 && isMatrixParams(commands[0])) {
var /** @type {?} */ p = segmentGroup.segments[startIndex];
paths.push(new UrlSegment(p.path, commands[0]));
i++;
continue;
}
var /** @type {?} */ curr = getPath(commands[i]);
var /** @type {?} */ next = (i < commands.length - 1) ? commands[i + 1] : null;
if (curr && next && isMatrixParams(next)) {
paths.push(new UrlSegment(curr, stringify(next)));
i += 2;
}
else {
paths.push(new UrlSegment(curr, {}));
i++;
}
}
return new UrlSegmentGroup(paths, {});
}
/**
* @param {?} outlets
* @return {?}
*/
function createNewSegmentChildren(outlets) {
var /** @type {?} */ children = {};
forEach(outlets, function (commands, outlet) {
if (commands !== null) {
children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);
}
});
return children;
}
/**
* @param {?} params
* @return {?}
*/
function stringify(params) {
var /** @type {?} */ res = {};
forEach(params, function (v, k) { return res[k] = "" + v; });
return res;
}
/**
* @param {?} path
* @param {?} params
* @param {?} segment
* @return {?}
*/
function compare(path, params, segment) {
return path == segment.path && shallowEqual(params, segment.parameters);
}
/**
* @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
*/
var __assign$3 = (undefined && undefined.__assign) || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var NoMatch$1 = (function () {
function NoMatch$1() {
}
return NoMatch$1;
}());
/**
* @param {?} rootComponentType
* @param {?} config
* @param {?} urlTree
* @param {?} url
* @return {?}
*/
function recognize(rootComponentType, config, urlTree, url) {
return new Recognizer(rootComponentType, config, urlTree, url).recognize();
}
var Recognizer = (function () {
/**
* @param {?} rootComponentType
* @param {?} config
* @param {?} urlTree
* @param {?} url
*/
function Recognizer(rootComponentType, config, urlTree, url) {
this.rootComponentType = rootComponentType;
this.config = config;
this.urlTree = urlTree;
this.url = url;
}
/**
* @return {?}
*/
Recognizer.prototype.recognize = function () {
try {
var /** @type {?} */ rootSegmentGroup = split$1(this.urlTree.root, [], [], this.config).segmentGroup;
var /** @type {?} */ children = this.processSegmentGroup(this.config, rootSegmentGroup, PRIMARY_OUTLET);
var /** @type {?} */ root = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), {}, PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, {});
var /** @type {?} */ rootNode = new TreeNode(root, children);
var /** @type {?} */ routeState = new RouterStateSnapshot(this.url, rootNode);
this.inheriteParamsAndData(routeState._root);
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(routeState);
}
catch (e) {
return new __WEBPACK_IMPORTED_MODULE_12_rxjs_Observable__["Observable"](function (obs) { return obs.error(e); });
}
};
/**
* @param {?} routeNode
* @return {?}
*/
Recognizer.prototype.inheriteParamsAndData = function (routeNode) {
var _this = this;
var /** @type {?} */ route = routeNode.value;
var /** @type {?} */ i = inheritedParamsDataResolve(route);
route.params = Object.freeze(i.params);
route.data = Object.freeze(i.data);
routeNode.children.forEach(function (n) { return _this.inheriteParamsAndData(n); });
};
/**
* @param {?} config
* @param {?} segmentGroup
* @param {?} outlet
* @return {?}
*/
Recognizer.prototype.processSegmentGroup = function (config, segmentGroup, outlet) {
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return this.processChildren(config, segmentGroup);
}
return this.processSegment(config, segmentGroup, segmentGroup.segments, outlet);
};
/**
* @param {?} config
* @param {?} segmentGroup
* @return {?}
*/
Recognizer.prototype.processChildren = function (config, segmentGroup) {
var _this = this;
var /** @type {?} */ children = mapChildrenIntoArray(segmentGroup, function (child, childOutlet) { return _this.processSegmentGroup(config, child, childOutlet); });
checkOutletNameUniqueness(children);
sortActivatedRouteSnapshots(children);
return children;
};
/**
* @param {?} config
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
Recognizer.prototype.processSegment = function (config, segmentGroup, segments, outlet) {
for (var _i = 0, config_1 = config; _i < config_1.length; _i++) {
var r = config_1[_i];
try {
return this.processSegmentAgainstRoute(r, segmentGroup, segments, outlet);
}
catch (e) {
if (!(e instanceof NoMatch$1))
throw e;
}
}
if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
return [];
}
throw new NoMatch$1();
};
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
Recognizer.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) {
return segments.length === 0 && !segmentGroup.children[outlet];
};
/**
* @param {?} route
* @param {?} rawSegment
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
Recognizer.prototype.processSegmentAgainstRoute = function (route, rawSegment, segments, outlet) {
if (route.redirectTo)
throw new NoMatch$1();
if ((route.outlet || PRIMARY_OUTLET) !== outlet)
throw new NoMatch$1();
if (route.path === '**') {
var /** @type {?} */ params = segments.length > 0 ? ((last$1(segments))).parameters : {};
var /** @type {?} */ snapshot_1 = new ActivatedRouteSnapshot(segments, params, Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), getData(route), outlet, /** @type {?} */ ((route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + segments.length, getResolve(route));
return [new TreeNode(snapshot_1, [])];
}
var _a = match$1(rawSegment, route, segments), consumedSegments = _a.consumedSegments, parameters = _a.parameters, lastChild = _a.lastChild;
var /** @type {?} */ rawSlicedSegments = segments.slice(lastChild);
var /** @type {?} */ childConfig = getChildConfig(route);
var _b = split$1(rawSegment, consumedSegments, rawSlicedSegments, childConfig), segmentGroup = _b.segmentGroup, slicedSegments = _b.slicedSegments;
var /** @type {?} */ snapshot = new ActivatedRouteSnapshot(consumedSegments, parameters, Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), getData(route), outlet, /** @type {?} */ ((route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length, getResolve(route));
if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
var /** @type {?} */ children_3 = this.processChildren(childConfig, segmentGroup);
return [new TreeNode(snapshot, children_3)];
}
if (childConfig.length === 0 && slicedSegments.length === 0) {
return [new TreeNode(snapshot, [])];
}
var /** @type {?} */ children = this.processSegment(childConfig, segmentGroup, slicedSegments, PRIMARY_OUTLET);
return [new TreeNode(snapshot, children)];
};
return Recognizer;
}());
/**
* @param {?} nodes
* @return {?}
*/
function sortActivatedRouteSnapshots(nodes) {
nodes.sort(function (a, b) {
if (a.value.outlet === PRIMARY_OUTLET)
return -1;
if (b.value.outlet === PRIMARY_OUTLET)
return 1;
return a.value.outlet.localeCompare(b.value.outlet);
});
}
/**
* @param {?} route
* @return {?}
*/
function getChildConfig(route) {
if (route.children) {
return route.children;
}
if (route.loadChildren) {
return ((route._loadedConfig)).routes;
}
return [];
}
/**
* @param {?} segmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
function match$1(segmentGroup, route, segments) {
if (route.path === '') {
if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
throw new NoMatch$1();
}
return { consumedSegments: [], lastChild: 0, parameters: {} };
}
var /** @type {?} */ matcher = route.matcher || defaultUrlMatcher;
var /** @type {?} */ res = matcher(segments, segmentGroup, route);
if (!res)
throw new NoMatch$1();
var /** @type {?} */ posParams = {};
forEach(/** @type {?} */ ((res.posParams)), function (v, k) { posParams[k] = v.path; });
var /** @type {?} */ parameters = __assign$3({}, posParams, res.consumed[res.consumed.length - 1].parameters);
return { consumedSegments: res.consumed, lastChild: res.consumed.length, parameters: parameters };
}
/**
* @param {?} nodes
* @return {?}
*/
function checkOutletNameUniqueness(nodes) {
var /** @type {?} */ names = {};
nodes.forEach(function (n) {
var /** @type {?} */ routeWithSameOutletName = names[n.value.outlet];
if (routeWithSameOutletName) {
var /** @type {?} */ p = routeWithSameOutletName.url.map(function (s) { return s.toString(); }).join('/');
var /** @type {?} */ c = n.value.url.map(function (s) { return s.toString(); }).join('/');
throw new Error("Two segments cannot have the same outlet name: '" + p + "' and '" + c + "'.");
}
names[n.value.outlet] = n.value;
});
}
/**
* @param {?} segmentGroup
* @return {?}
*/
function getSourceSegmentGroup(segmentGroup) {
var /** @type {?} */ s = segmentGroup;
while (s._sourceSegment) {
s = s._sourceSegment;
}
return s;
}
/**
* @param {?} segmentGroup
* @return {?}
*/
function getPathIndexShift(segmentGroup) {
var /** @type {?} */ s = segmentGroup;
var /** @type {?} */ res = (s._segmentIndexShift ? s._segmentIndexShift : 0);
while (s._sourceSegment) {
s = s._sourceSegment;
res += (s._segmentIndexShift ? s._segmentIndexShift : 0);
}
return res - 1;
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} slicedSegments
* @param {?} config
* @return {?}
*/
function split$1(segmentGroup, consumedSegments, slicedSegments, config) {
if (slicedSegments.length > 0 &&
containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {
var /** @type {?} */ s_1 = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(segmentGroup, consumedSegments, config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
s_1._sourceSegment = segmentGroup;
s_1._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s_1, slicedSegments: [] };
}
if (slicedSegments.length === 0 &&
containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {
var /** @type {?} */ s_2 = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
s_2._sourceSegment = segmentGroup;
s_2._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s_2, slicedSegments: slicedSegments };
}
var /** @type {?} */ s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);
s._sourceSegment = segmentGroup;
s._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s, slicedSegments: slicedSegments };
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @param {?} children
* @return {?}
*/
function addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
var /** @type {?} */ res = {};
for (var _i = 0, routes_3 = routes; _i < routes_3.length; _i++) {
var r = routes_3[_i];
if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet$2(r)]) {
var /** @type {?} */ s = new UrlSegmentGroup([], {});
s._sourceSegment = segmentGroup;
s._segmentIndexShift = segmentGroup.segments.length;
res[getOutlet$2(r)] = s;
}
}
return __assign$3({}, children, res);
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} routes
* @param {?} primarySegment
* @return {?}
*/
function createChildrenForEmptyPaths(segmentGroup, consumedSegments, routes, primarySegment) {
var /** @type {?} */ res = {};
res[PRIMARY_OUTLET] = primarySegment;
primarySegment._sourceSegment = segmentGroup;
primarySegment._segmentIndexShift = consumedSegments.length;
for (var _i = 0, routes_4 = routes; _i < routes_4.length; _i++) {
var r = routes_4[_i];
if (r.path === '' && getOutlet$2(r) !== PRIMARY_OUTLET) {
var /** @type {?} */ s = new UrlSegmentGroup([], {});
s._sourceSegment = segmentGroup;
s._segmentIndexShift = consumedSegments.length;
res[getOutlet$2(r)] = s;
}
}
return res;
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {
return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet$2(r) !== PRIMARY_OUTLET; });
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {
return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r); });
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} r
* @return {?}
*/
function emptyPathMatch(segmentGroup, slicedSegments, r) {
if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {
return false;
}
return r.path === '' && r.redirectTo === undefined;
}
/**
* @param {?} route
* @return {?}
*/
function getOutlet$2(route) {
return route.outlet || PRIMARY_OUTLET;
}
/**
* @param {?} route
* @return {?}
*/
function getData(route) {
return route.data || {};
}
/**
* @param {?} route
* @return {?}
*/
function getResolve(route) {
return route.resolve || {};
}
/**
* @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
*/
/**
* \@docsNotRequired
* \@experimental
*/
var ROUTES = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["e" /* InjectionToken */]('ROUTES');
var RouterConfigLoader = (function () {
/**
* @param {?} loader
* @param {?} compiler
* @param {?=} onLoadStartListener
* @param {?=} onLoadEndListener
*/
function RouterConfigLoader(loader, compiler, onLoadStartListener, onLoadEndListener) {
this.loader = loader;
this.compiler = compiler;
this.onLoadStartListener = onLoadStartListener;
this.onLoadEndListener = onLoadEndListener;
}
/**
* @param {?} parentInjector
* @param {?} route
* @return {?}
*/
RouterConfigLoader.prototype.load = function (parentInjector, route) {
var _this = this;
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
var /** @type {?} */ moduleFactory$ = this.loadModuleFactory(/** @type {?} */ ((route.loadChildren)));
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(moduleFactory$, function (factory) {
if (_this.onLoadEndListener) {
_this.onLoadEndListener(route);
}
var /** @type {?} */ module = factory.create(parentInjector);
return new LoadedRouterConfig(flatten(module.injector.get(ROUTES)), module);
});
};
/**
* @param {?} loadChildren
* @return {?}
*/
RouterConfigLoader.prototype.loadModuleFactory = function (loadChildren) {
var _this = this;
if (typeof loadChildren === 'string') {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_16_rxjs_observable_fromPromise__["fromPromise"])(this.loader.load(loadChildren));
}
else {
return __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(wrapIntoObservable(loadChildren()), function (t) {
if (t instanceof __WEBPACK_IMPORTED_MODULE_1__angular_core__["_5" /* NgModuleFactory */]) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(t);
}
else {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_16_rxjs_observable_fromPromise__["fromPromise"])(_this.compiler.compileModuleAsync(t));
}
});
}
};
return RouterConfigLoader;
}());
/**
* @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
*/
/**
* \@whatItDoes Contains all the router outlets created in a component.
*
* \@stable
*/
var RouterOutletMap = (function () {
function RouterOutletMap() {
/**
* \@internal
*/
this._outlets = {};
}
/**
* Adds an outlet to this map.
* @param {?} name
* @param {?} outlet
* @return {?}
*/
RouterOutletMap.prototype.registerOutlet = function (name, outlet) { this._outlets[name] = outlet; };
/**
* Removes an outlet from this map.
* @param {?} name
* @return {?}
*/
RouterOutletMap.prototype.removeOutlet = function (name) { this._outlets[name] = ((undefined)); };
return RouterOutletMap;
}());
/**
* @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
*/
/**
* \@whatItDoes Provides a way to migrate AngularJS applications to Angular.
*
* \@experimental
* @abstract
*/
var UrlHandlingStrategy = (function () {
function UrlHandlingStrategy() {
}
/**
* Tells the router if this URL should be processed.
*
* When it returns true, the router will execute the regular navigation.
* When it returns false, the router will set the router state to an empty state.
* As a result, all the active components will be destroyed.
*
* @abstract
* @param {?} url
* @return {?}
*/
UrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { };
/**
* Extracts the part of the URL that should be handled by the router.
* The rest of the URL will remain untouched.
* @abstract
* @param {?} url
* @return {?}
*/
UrlHandlingStrategy.prototype.extract = function (url) { };
/**
* Merges the URL fragment with the rest of the URL.
* @abstract
* @param {?} newUrlPart
* @param {?} rawUrl
* @return {?}
*/
UrlHandlingStrategy.prototype.merge = function (newUrlPart, rawUrl) { };
return UrlHandlingStrategy;
}());
/**
* \@experimental
*/
var DefaultUrlHandlingStrategy = (function () {
function DefaultUrlHandlingStrategy() {
}
/**
* @param {?} url
* @return {?}
*/
DefaultUrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { return true; };
/**
* @param {?} url
* @return {?}
*/
DefaultUrlHandlingStrategy.prototype.extract = function (url) { return url; };
/**
* @param {?} newUrlPart
* @param {?} wholeUrl
* @return {?}
*/
DefaultUrlHandlingStrategy.prototype.merge = function (newUrlPart, wholeUrl) { return newUrlPart; };
return DefaultUrlHandlingStrategy;
}());
/**
* @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
*/
var __assign = (undefined && undefined.__assign) || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
/**
* @param {?} error
* @return {?}
*/
function defaultErrorHandler(error) {
throw error;
}
/**
* \@internal
* @param {?} snapshot
* @return {?}
*/
function defaultRouterHook(snapshot) {
return (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(null));
}
/**
* Does not detach any subtrees. Reuses routes as long as their route config is the same.
*/
var DefaultRouteReuseStrategy = (function () {
function DefaultRouteReuseStrategy() {
}
/**
* @param {?} route
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.shouldDetach = function (route) { return false; };
/**
* @param {?} route
* @param {?} detachedTree
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.store = function (route, detachedTree) { };
/**
* @param {?} route
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.shouldAttach = function (route) { return false; };
/**
* @param {?} route
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.retrieve = function (route) { return null; };
/**
* @param {?} future
* @param {?} curr
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) {
return future.routeConfig === curr.routeConfig;
};
return DefaultRouteReuseStrategy;
}());
/**
* \@whatItDoes Provides the navigation and url manipulation capabilities.
*
* See {\@link Routes} for more details and examples.
*
* \@ngModule RouterModule
*
* \@stable
*/
var Router = (function () {
/**
* @param {?} rootComponentType
* @param {?} urlSerializer
* @param {?} outletMap
* @param {?} location
* @param {?} injector
* @param {?} loader
* @param {?} compiler
* @param {?} config
*/
function Router(rootComponentType, urlSerializer, outletMap, location, injector, loader, compiler, config) {
var _this = this;
this.rootComponentType = rootComponentType;
this.urlSerializer = urlSerializer;
this.outletMap = outletMap;
this.location = location;
this.config = config;
this.navigations = new __WEBPACK_IMPORTED_MODULE_2_rxjs_BehaviorSubject__["BehaviorSubject"](/** @type {?} */ ((null)));
this.routerEvents = new __WEBPACK_IMPORTED_MODULE_3_rxjs_Subject__["Subject"]();
this.navigationId = 0;
/**
* Error handler that is invoked when a navigation errors.
*
* See {@link ErrorHandler} for more information.
*/
this.errorHandler = defaultErrorHandler;
/**
* Indicates if at least one navigation happened.
*/
this.navigated = false;
/**
* Used by RouterModule. This allows us to
* pause the navigation either before preactivation or after it.
* \@internal
*/
this.hooks = {
beforePreactivation: defaultRouterHook,
afterPreactivation: defaultRouterHook
};
/**
* Extracts and merges URLs. Used for AngularJS to Angular migrations.
*/
this.urlHandlingStrategy = new DefaultUrlHandlingStrategy();
this.routeReuseStrategy = new DefaultRouteReuseStrategy();
var onLoadStart = function (r) { return _this.triggerEvent(new RouteConfigLoadStart(r)); };
var onLoadEnd = function (r) { return _this.triggerEvent(new RouteConfigLoadEnd(r)); };
this.ngModule = injector.get(__WEBPACK_IMPORTED_MODULE_1__angular_core__["V" /* NgModuleRef */]);
this.resetConfig(config);
this.currentUrlTree = createEmptyUrlTree();
this.rawUrlTree = this.currentUrlTree;
this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd);
this.currentRouterState = createEmptyState(this.currentUrlTree, this.rootComponentType);
this.processNavigations();
}
/**
* \@internal
* TODO: this should be removed once the constructor of the router made internal
* @param {?} rootComponentType
* @return {?}
*/
Router.prototype.resetRootComponentType = function (rootComponentType) {
this.rootComponentType = rootComponentType;
// TODO: vsavkin router 4.0 should make the root component set to null
// this will simplify the lifecycle of the router.
this.currentRouterState.root.component = this.rootComponentType;
};
/**
* Sets up the location change listener and performs the initial navigation.
* @return {?}
*/
Router.prototype.initialNavigation = function () {
this.setUpLocationChangeListener();
if (this.navigationId === 0) {
this.navigateByUrl(this.location.path(true), { replaceUrl: true });
}
};
/**
* Sets up the location change listener.
* @return {?}
*/
Router.prototype.setUpLocationChangeListener = function () {
var _this = this;
// Zone.current.wrap is needed because of the issue with RxJS scheduler,
// which does not work properly with zone.js in IE and Safari
if (!this.locationSubscription) {
this.locationSubscription = (this.location.subscribe(Zone.current.wrap(function (change) {
var /** @type {?} */ rawUrlTree = _this.urlSerializer.parse(change['url']);
var /** @type {?} */ source = change['type'] === 'popstate' ? 'popstate' : 'hashchange';
setTimeout(function () { _this.scheduleNavigation(rawUrlTree, source, { replaceUrl: true }); }, 0);
})));
}
};
Object.defineProperty(Router.prototype, "routerState", {
/**
* The current route state
* @return {?}
*/
get: function () { return this.currentRouterState; },
enumerable: true,
configurable: true
});
Object.defineProperty(Router.prototype, "url", {
/**
* The current url
* @return {?}
*/
get: function () { return this.serializeUrl(this.currentUrlTree); },
enumerable: true,
configurable: true
});
Object.defineProperty(Router.prototype, "events", {
/**
* An observable of router events
* @return {?}
*/
get: function () { return this.routerEvents; },
enumerable: true,
configurable: true
});
/**
* \@internal
* @param {?} e
* @return {?}
*/
Router.prototype.triggerEvent = function (e) { this.routerEvents.next(e); };
/**
* Resets the configuration used for navigation and generating links.
*
* ### Usage
*
* ```
* router.resetConfig([
* { path: 'team/:id', component: TeamCmp, children: [
* { path: 'simple', component: SimpleCmp },
* { path: 'user/:name', component: UserCmp }
* ]}
* ]);
* ```
* @param {?} config
* @return {?}
*/
Router.prototype.resetConfig = function (config) {
validateConfig(config);
this.config = config;
};
/**
* \@docsNotRequired
* @return {?}
*/
Router.prototype.ngOnDestroy = function () { this.dispose(); };
/**
* Disposes of the router
* @return {?}
*/
Router.prototype.dispose = function () {
if (this.locationSubscription) {
this.locationSubscription.unsubscribe();
this.locationSubscription = ((null));
}
};
/**
* Applies an array of commands to the current url tree and creates a new url tree.
*
* When given an activate route, applies the given commands starting from the route.
* When not given a route, applies the given command starting from the root.
*
* ### Usage
*
* ```
* // create /team/33/user/11
* router.createUrlTree(['/team', 33, 'user', 11]);
*
* // create /team/33;expand=true/user/11
* router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
*
* // you can collapse static segments like this (this works only with the first passed-in value):
* router.createUrlTree(['/team/33/user', userId]);
*
* // If the first segment can contain slashes, and you do not want the router to split it, you
* // can do the following:
*
* router.createUrlTree([{segmentPath: '/one/two'}]);
*
* // create /team/33/(user/11//right:chat)
* router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
*
* // remove the right secondary node
* router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
*
* // assuming the current url is `/team/33/user/11` and the route points to `user/11`
*
* // navigate to /team/33/user/11/details
* router.createUrlTree(['details'], {relativeTo: route});
*
* // navigate to /team/33/user/22
* router.createUrlTree(['../22'], {relativeTo: route});
*
* // navigate to /team/44/user/22
* router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
* ```
* @param {?} commands
* @param {?=} __1
* @return {?}
*/
Router.prototype.createUrlTree = function (commands, _a) {
var _b = _a === void 0 ? {} : _a, relativeTo = _b.relativeTo, queryParams = _b.queryParams, fragment = _b.fragment, preserveQueryParams = _b.preserveQueryParams, queryParamsHandling = _b.queryParamsHandling, preserveFragment = _b.preserveFragment;
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["E" /* isDevMode */])() && preserveQueryParams && (console) && (console.warn)) {
console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
}
var /** @type {?} */ a = relativeTo || this.routerState.root;
var /** @type {?} */ f = preserveFragment ? this.currentUrlTree.fragment : fragment;
var /** @type {?} */ q = null;
if (queryParamsHandling) {
switch (queryParamsHandling) {
case 'merge':
q = __assign({}, this.currentUrlTree.queryParams, queryParams);
break;
case 'preserve':
q = this.currentUrlTree.queryParams;
break;
default:
q = queryParams || null;
}
}
else {
q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams || null;
}
return createUrlTree(a, this.currentUrlTree, commands, /** @type {?} */ ((q)), /** @type {?} */ ((f)));
};
/**
* Navigate based on the provided url. This navigation is always absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigateByUrl("/team/33/user/11");
*
* // Navigate without updating the URL
* router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
* ```
*
* In opposite to `navigate`, `navigateByUrl` takes a whole URL
* and does not apply any delta to the current one.
* @param {?} url
* @param {?=} extras
* @return {?}
*/
Router.prototype.navigateByUrl = function (url, extras) {
if (extras === void 0) { extras = { skipLocationChange: false }; }
var /** @type {?} */ urlTree = url instanceof UrlTree ? url : this.parseUrl(url);
var /** @type {?} */ mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);
return this.scheduleNavigation(mergedTree, 'imperative', extras);
};
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
* URL.
* @param {?} commands
* @param {?=} extras
* @return {?}
*/
Router.prototype.navigate = function (commands, extras) {
if (extras === void 0) { extras = { skipLocationChange: false }; }
validateCommands(commands);
if (typeof extras.queryParams === 'object' && extras.queryParams !== null) {
extras.queryParams = this.removeEmptyProps(extras.queryParams);
}
return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
};
/**
* Serializes a {\@link UrlTree} into a string
* @param {?} url
* @return {?}
*/
Router.prototype.serializeUrl = function (url) { return this.urlSerializer.serialize(url); };
/**
* Parses a string into a {\@link UrlTree}
* @param {?} url
* @return {?}
*/
Router.prototype.parseUrl = function (url) { return this.urlSerializer.parse(url); };
/**
* Returns whether the url is activated
* @param {?} url
* @param {?} exact
* @return {?}
*/
Router.prototype.isActive = function (url, exact) {
if (url instanceof UrlTree) {
return containsTree(this.currentUrlTree, url, exact);
}
else {
var /** @type {?} */ urlTree = this.urlSerializer.parse(url);
return containsTree(this.currentUrlTree, urlTree, exact);
}
};
/**
* @param {?} params
* @return {?}
*/
Router.prototype.removeEmptyProps = function (params) {
return Object.keys(params).reduce(function (result, key) {
var /** @type {?} */ value = params[key];
if (value !== null && value !== undefined) {
result[key] = value;
}
return result;
}, {});
};
/**
* @return {?}
*/
Router.prototype.processNavigations = function () {
var _this = this;
__WEBPACK_IMPORTED_MODULE_6_rxjs_operator_concatMap__["concatMap"]
.call(this.navigations, function (nav) {
if (nav) {
_this.executeScheduledNavigation(nav);
// a failed navigation should not stop the router from processing
// further navigations => the catch
return nav.promise.catch(function () { });
}
else {
return (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(null));
}
})
.subscribe(function () { });
};
/**
* @param {?} rawUrl
* @param {?} source
* @param {?} extras
* @return {?}
*/
Router.prototype.scheduleNavigation = function (rawUrl, source, extras) {
var /** @type {?} */ lastNavigation = this.navigations.value;
// If the user triggers a navigation imperatively (e.g., by using navigateByUrl),
// and that navigation results in 'replaceState' that leads to the same URL,
// we should skip those.
if (lastNavigation && source !== 'imperative' && lastNavigation.source === 'imperative' &&
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
return Promise.resolve(true); // return value is not used
}
// Because of a bug in IE and Edge, the location class fires two events (popstate and
// hashchange) every single time. The second one should be ignored. Otherwise, the URL will
// flicker.
if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' &&
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
return Promise.resolve(true); // return value is not used
}
var /** @type {?} */ resolve = null;
var /** @type {?} */ reject = null;
var /** @type {?} */ promise = new Promise(function (res, rej) {
resolve = res;
reject = rej;
});
var /** @type {?} */ id = ++this.navigationId;
this.navigations.next({ id: id, source: source, rawUrl: rawUrl, extras: extras, resolve: resolve, reject: reject, promise: promise });
// Make sure that the error is propagated even though `processNavigations` catch
// handler does not rethrow
return promise.catch(function (e) { return Promise.reject(e); });
};
/**
* @param {?} __0
* @return {?}
*/
Router.prototype.executeScheduledNavigation = function (_a) {
var _this = this;
var id = _a.id, rawUrl = _a.rawUrl, extras = _a.extras, resolve = _a.resolve, reject = _a.reject;
var /** @type {?} */ url = this.urlHandlingStrategy.extract(rawUrl);
var /** @type {?} */ urlTransition = !this.navigated || url.toString() !== this.currentUrlTree.toString();
if (urlTransition && this.urlHandlingStrategy.shouldProcessUrl(rawUrl)) {
this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url)));
Promise.resolve()
.then(function (_) { return _this.runNavigate(url, rawUrl, !!extras.skipLocationChange, !!extras.replaceUrl, id, null); })
.then(resolve, reject);
}
else if (urlTransition && this.rawUrlTree &&
this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree)) {
this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url)));
Promise.resolve()
.then(function (_) { return _this.runNavigate(url, rawUrl, false, false, id, createEmptyState(url, _this.rootComponentType).snapshot); })
.then(resolve, reject);
}
else {
this.rawUrlTree = rawUrl;
resolve(null);
}
};
/**
* @param {?} url
* @param {?} rawUrl
* @param {?} shouldPreventPushState
* @param {?} shouldReplaceUrl
* @param {?} id
* @param {?} precreatedState
* @return {?}
*/
Router.prototype.runNavigate = function (url, rawUrl, shouldPreventPushState, shouldReplaceUrl, id, precreatedState) {
var _this = this;
if (id !== this.navigationId) {
this.location.go(this.urlSerializer.serialize(this.currentUrlTree));
this.routerEvents.next(new NavigationCancel(id, this.serializeUrl(url), "Navigation ID " + id + " is not equal to the current navigation id " + this.navigationId));
return Promise.resolve(false);
}
return new Promise(function (resolvePromise, rejectPromise) {
// create an observable of the url and route state snapshot
// this operation do not result in any side effects
var /** @type {?} */ urlAndSnapshot$;
if (!precreatedState) {
var /** @type {?} */ moduleInjector = _this.ngModule.injector;
var /** @type {?} */ redirectsApplied$ = applyRedirects(moduleInjector, _this.configLoader, _this.urlSerializer, url, _this.config);
urlAndSnapshot$ = __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(redirectsApplied$, function (appliedUrl) {
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(recognize(_this.rootComponentType, _this.config, appliedUrl, _this.serializeUrl(appliedUrl)), function (snapshot) {
_this.routerEvents.next(new RoutesRecognized(id, _this.serializeUrl(url), _this.serializeUrl(appliedUrl), snapshot));
return { appliedUrl: appliedUrl, snapshot: snapshot };
});
});
}
else {
urlAndSnapshot$ = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])({ appliedUrl: url, snapshot: precreatedState });
}
var /** @type {?} */ beforePreactivationDone$ = __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(urlAndSnapshot$, function (p) {
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(_this.hooks.beforePreactivation(p.snapshot), function () { return p; });
});
// run preactivation: guards and data resolvers
var /** @type {?} */ preActivation;
var /** @type {?} */ preactivationTraverse$ = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(beforePreactivationDone$, function (_a) {
var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot;
var /** @type {?} */ moduleInjector = _this.ngModule.injector;
preActivation =
new PreActivation(snapshot, _this.currentRouterState.snapshot, moduleInjector);
preActivation.traverse(_this.outletMap);
return { appliedUrl: appliedUrl, snapshot: snapshot };
});
var /** @type {?} */ preactivationCheckGuards$ = __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(preactivationTraverse$, function (_a) {
var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot;
if (_this.navigationId !== id)
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(false);
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(preActivation.checkGuards(), function (shouldActivate) {
return { appliedUrl: appliedUrl, snapshot: snapshot, shouldActivate: shouldActivate };
});
});
var /** @type {?} */ preactivationResolveData$ = __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(preactivationCheckGuards$, function (p) {
if (_this.navigationId !== id)
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(false);
if (p.shouldActivate) {
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(preActivation.resolveData(), function () { return p; });
}
else {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(p);
}
});
var /** @type {?} */ preactivationDone$ = __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(preactivationResolveData$, function (p) {
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(_this.hooks.afterPreactivation(p.snapshot), function () { return p; });
});
// create router state
// this operation has side effects => route state is being affected
var /** @type {?} */ routerState$ = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(preactivationDone$, function (_a) {
var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot, shouldActivate = _a.shouldActivate;
if (shouldActivate) {
var /** @type {?} */ state = createRouterState(_this.routeReuseStrategy, snapshot, _this.currentRouterState);
return { appliedUrl: appliedUrl, state: state, shouldActivate: shouldActivate };
}
else {
return { appliedUrl: appliedUrl, state: null, shouldActivate: shouldActivate };
}
});
// applied the new router state
// this operation has side effects
var /** @type {?} */ navigationIsSuccessful;
var /** @type {?} */ storedState = _this.currentRouterState;
var /** @type {?} */ storedUrl = _this.currentUrlTree;
routerState$
.forEach(function (_a) {
var appliedUrl = _a.appliedUrl, state = _a.state, shouldActivate = _a.shouldActivate;
if (!shouldActivate || id !== _this.navigationId) {
navigationIsSuccessful = false;
return;
}
_this.currentUrlTree = appliedUrl;
_this.rawUrlTree = _this.urlHandlingStrategy.merge(_this.currentUrlTree, rawUrl);
_this.currentRouterState = state;
if (!shouldPreventPushState) {
var /** @type {?} */ path = _this.urlSerializer.serialize(_this.rawUrlTree);
if (_this.location.isCurrentPathEqualTo(path) || shouldReplaceUrl) {
_this.location.replaceState(path);
}
else {
_this.location.go(path);
}
}
new ActivateRoutes(_this.routeReuseStrategy, state, storedState)
.activate(_this.outletMap);
navigationIsSuccessful = true;
})
.then(function () {
if (navigationIsSuccessful) {
_this.navigated = true;
_this.routerEvents.next(new NavigationEnd(id, _this.serializeUrl(url), _this.serializeUrl(_this.currentUrlTree)));
resolvePromise(true);
}
else {
_this.resetUrlToCurrentUrlTree();
_this.routerEvents.next(new NavigationCancel(id, _this.serializeUrl(url), ''));
resolvePromise(false);
}
}, function (e) {
if (isNavigationCancelingError(e)) {
_this.resetUrlToCurrentUrlTree();
_this.navigated = true;
_this.routerEvents.next(new NavigationCancel(id, _this.serializeUrl(url), e.message));
resolvePromise(false);
}
else {
_this.routerEvents.next(new NavigationError(id, _this.serializeUrl(url), e));
try {
resolvePromise(_this.errorHandler(e));
}
catch (ee) {
rejectPromise(ee);
}
}
_this.currentRouterState = storedState;
_this.currentUrlTree = storedUrl;
_this.rawUrlTree = _this.urlHandlingStrategy.merge(_this.currentUrlTree, rawUrl);
_this.location.replaceState(_this.serializeUrl(_this.rawUrlTree));
});
});
};
/**
* @return {?}
*/
Router.prototype.resetUrlToCurrentUrlTree = function () {
var /** @type {?} */ path = this.urlSerializer.serialize(this.rawUrlTree);
this.location.replaceState(path);
};
return Router;
}());
var CanActivate = (function () {
/**
* @param {?} path
*/
function CanActivate(path) {
this.path = path;
}
Object.defineProperty(CanActivate.prototype, "route", {
/**
* @return {?}
*/
get: function () { return this.path[this.path.length - 1]; },
enumerable: true,
configurable: true
});
return CanActivate;
}());
var CanDeactivate = (function () {
/**
* @param {?} component
* @param {?} route
*/
function CanDeactivate(component, route) {
this.component = component;
this.route = route;
}
return CanDeactivate;
}());
var PreActivation = (function () {
/**
* @param {?} future
* @param {?} curr
* @param {?} moduleInjector
*/
function PreActivation(future, curr, moduleInjector) {
this.future = future;
this.curr = curr;
this.moduleInjector = moduleInjector;
this.canActivateChecks = [];
this.canDeactivateChecks = [];
}
/**
* @param {?} parentOutletMap
* @return {?}
*/
PreActivation.prototype.traverse = function (parentOutletMap) {
var /** @type {?} */ futureRoot = this.future._root;
var /** @type {?} */ currRoot = this.curr ? this.curr._root : null;
this.traverseChildRoutes(futureRoot, currRoot, parentOutletMap, [futureRoot.value]);
};
/**
* @return {?}
*/
PreActivation.prototype.checkGuards = function () {
var _this = this;
if (this.canDeactivateChecks.length === 0 && this.canActivateChecks.length === 0) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(true);
}
var /** @type {?} */ canDeactivate$ = this.runCanDeactivateChecks();
return __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(canDeactivate$, function (canDeactivate) { return canDeactivate ? _this.runCanActivateChecks() : __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(false); });
};
/**
* @return {?}
*/
PreActivation.prototype.resolveData = function () {
var _this = this;
if (this.canActivateChecks.length === 0)
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(null);
var /** @type {?} */ checks$ = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(this.canActivateChecks);
var /** @type {?} */ runningChecks$ = __WEBPACK_IMPORTED_MODULE_6_rxjs_operator_concatMap__["concatMap"].call(checks$, function (check) { return _this.runResolve(check.route); });
return __WEBPACK_IMPORTED_MODULE_11_rxjs_operator_reduce__["reduce"].call(runningChecks$, function (_, __) { return _; });
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} outletMap
* @param {?} futurePath
* @return {?}
*/
PreActivation.prototype.traverseChildRoutes = function (futureNode, currNode, outletMap, futurePath) {
var _this = this;
var /** @type {?} */ prevChildren = nodeChildrenAsMap(currNode);
futureNode.children.forEach(function (c) {
_this.traverseRoutes(c, prevChildren[c.value.outlet], outletMap, futurePath.concat([c.value]));
delete prevChildren[c.value.outlet];
});
forEach(prevChildren, function (v, k) { return _this.deactiveRouteAndItsChildren(v, /** @type {?} */ ((outletMap))._outlets[k]); });
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentOutletMap
* @param {?} futurePath
* @return {?}
*/
PreActivation.prototype.traverseRoutes = function (futureNode, currNode, parentOutletMap, futurePath) {
var /** @type {?} */ future = futureNode.value;
var /** @type {?} */ curr = currNode ? currNode.value : null;
var /** @type {?} */ outlet = parentOutletMap ? parentOutletMap._outlets[futureNode.value.outlet] : null;
// reusing the node
if (curr && future._routeConfig === curr._routeConfig) {
if (this.shouldRunGuardsAndResolvers(curr, future, /** @type {?} */ ((future._routeConfig)).runGuardsAndResolvers)) {
this.canActivateChecks.push(new CanActivate(futurePath));
this.canDeactivateChecks.push(new CanDeactivate(/** @type {?} */ ((outlet)).component, curr));
}
else {
// we need to set the data
future.data = curr.data;
future._resolvedData = curr._resolvedData;
}
// If we have a component, we need to go through an outlet.
if (future.component) {
this.traverseChildRoutes(futureNode, currNode, outlet ? outlet.outletMap : null, futurePath);
}
else {
this.traverseChildRoutes(futureNode, currNode, parentOutletMap, futurePath);
}
}
else {
if (curr) {
this.deactiveRouteAndItsChildren(currNode, outlet);
}
this.canActivateChecks.push(new CanActivate(futurePath));
// If we have a component, we need to go through an outlet.
if (future.component) {
this.traverseChildRoutes(futureNode, null, outlet ? outlet.outletMap : null, futurePath);
}
else {
this.traverseChildRoutes(futureNode, null, parentOutletMap, futurePath);
}
}
};
/**
* @param {?} curr
* @param {?} future
* @param {?} mode
* @return {?}
*/
PreActivation.prototype.shouldRunGuardsAndResolvers = function (curr, future, mode) {
switch (mode) {
case 'always':
return true;
case 'paramsOrQueryParamsChange':
return !equalParamsAndUrlSegments(curr, future) ||
!shallowEqual(curr.queryParams, future.queryParams);
case 'paramsChange':
default:
return !equalParamsAndUrlSegments(curr, future);
}
};
/**
* @param {?} route
* @param {?} outlet
* @return {?}
*/
PreActivation.prototype.deactiveRouteAndItsChildren = function (route, outlet) {
var _this = this;
var /** @type {?} */ prevChildren = nodeChildrenAsMap(route);
var /** @type {?} */ r = route.value;
forEach(prevChildren, function (v, k) {
if (!r.component) {
_this.deactiveRouteAndItsChildren(v, outlet);
}
else if (!!outlet) {
_this.deactiveRouteAndItsChildren(v, outlet.outletMap._outlets[k]);
}
else {
_this.deactiveRouteAndItsChildren(v, null);
}
});
if (!r.component) {
this.canDeactivateChecks.push(new CanDeactivate(null, r));
}
else if (outlet && outlet.isActivated) {
this.canDeactivateChecks.push(new CanDeactivate(outlet.component, r));
}
else {
this.canDeactivateChecks.push(new CanDeactivate(null, r));
}
};
/**
* @return {?}
*/
PreActivation.prototype.runCanDeactivateChecks = function () {
var _this = this;
var /** @type {?} */ checks$ = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(this.canDeactivateChecks);
var /** @type {?} */ runningChecks$ = __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(checks$, function (check) { return _this.runCanDeactivate(check.component, check.route); });
return __WEBPACK_IMPORTED_MODULE_7_rxjs_operator_every__["every"].call(runningChecks$, function (result) { return result === true; });
};
/**
* @return {?}
*/
PreActivation.prototype.runCanActivateChecks = function () {
var _this = this;
var /** @type {?} */ checks$ = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(this.canActivateChecks);
var /** @type {?} */ runningChecks$ = __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(checks$, function (check) { return andObservables(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])([_this.runCanActivateChild(check.path), _this.runCanActivate(check.route)])); });
return __WEBPACK_IMPORTED_MODULE_7_rxjs_operator_every__["every"].call(runningChecks$, function (result) { return result === true; });
};
/**
* @param {?} future
* @return {?}
*/
PreActivation.prototype.runCanActivate = function (future) {
var _this = this;
var /** @type {?} */ canActivate = future._routeConfig ? future._routeConfig.canActivate : null;
if (!canActivate || canActivate.length === 0)
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(true);
var /** @type {?} */ obs = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(canActivate), function (c) {
var /** @type {?} */ guard = _this.getToken(c, future);
var /** @type {?} */ observable;
if (guard.canActivate) {
observable = wrapIntoObservable(guard.canActivate(future, _this.future));
}
else {
observable = wrapIntoObservable(guard(future, _this.future));
}
return __WEBPACK_IMPORTED_MODULE_8_rxjs_operator_first__["first"].call(observable);
});
return andObservables(obs);
};
/**
* @param {?} path
* @return {?}
*/
PreActivation.prototype.runCanActivateChild = function (path) {
var _this = this;
var /** @type {?} */ future = path[path.length - 1];
var /** @type {?} */ canActivateChildGuards = path.slice(0, path.length - 1)
.reverse()
.map(function (p) { return _this.extractCanActivateChild(p); })
.filter(function (_) { return _ !== null; });
return andObservables(__WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(canActivateChildGuards), function (d) {
var /** @type {?} */ obs = __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(d.guards), function (c) {
var /** @type {?} */ guard = _this.getToken(c, d.node);
var /** @type {?} */ observable;
if (guard.canActivateChild) {
observable = wrapIntoObservable(guard.canActivateChild(future, _this.future));
}
else {
observable = wrapIntoObservable(guard(future, _this.future));
}
return __WEBPACK_IMPORTED_MODULE_8_rxjs_operator_first__["first"].call(observable);
});
return andObservables(obs);
}));
};
/**
* @param {?} p
* @return {?}
*/
PreActivation.prototype.extractCanActivateChild = function (p) {
var /** @type {?} */ canActivateChild = p._routeConfig ? p._routeConfig.canActivateChild : null;
if (!canActivateChild || canActivateChild.length === 0)
return null;
return { node: p, guards: canActivateChild };
};
/**
* @param {?} component
* @param {?} curr
* @return {?}
*/
PreActivation.prototype.runCanDeactivate = function (component, curr) {
var _this = this;
var /** @type {?} */ canDeactivate = curr && curr._routeConfig ? curr._routeConfig.canDeactivate : null;
if (!canDeactivate || canDeactivate.length === 0)
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(true);
var /** @type {?} */ canDeactivate$ = __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(canDeactivate), function (c) {
var /** @type {?} */ guard = _this.getToken(c, curr);
var /** @type {?} */ observable;
if (guard.canDeactivate) {
observable =
wrapIntoObservable(guard.canDeactivate(component, curr, _this.curr, _this.future));
}
else {
observable = wrapIntoObservable(guard(component, curr, _this.curr, _this.future));
}
return __WEBPACK_IMPORTED_MODULE_8_rxjs_operator_first__["first"].call(observable);
});
return __WEBPACK_IMPORTED_MODULE_7_rxjs_operator_every__["every"].call(canDeactivate$, function (result) { return result === true; });
};
/**
* @param {?} future
* @return {?}
*/
PreActivation.prototype.runResolve = function (future) {
var /** @type {?} */ resolve = future._resolve;
return __WEBPACK_IMPORTED_MODULE_9_rxjs_operator_map__["map"].call(this.resolveNode(resolve, future), function (resolvedData) {
future._resolvedData = resolvedData;
future.data = __assign({}, future.data, inheritedParamsDataResolve(future).resolve);
return null;
});
};
/**
* @param {?} resolve
* @param {?} future
* @return {?}
*/
PreActivation.prototype.resolveNode = function (resolve, future) {
var _this = this;
return waitForMap(resolve, function (k, v) {
var /** @type {?} */ resolver = _this.getToken(v, future);
return resolver.resolve ? wrapIntoObservable(resolver.resolve(future, _this.future)) :
wrapIntoObservable(resolver(future, _this.future));
});
};
/**
* @param {?} token
* @param {?} snapshot
* @return {?}
*/
PreActivation.prototype.getToken = function (token, snapshot) {
var /** @type {?} */ config = closestLoadedConfig(snapshot);
var /** @type {?} */ injector = config ? config.module.injector : this.moduleInjector;
return injector.get(token);
};
return PreActivation;
}());
var ActivateRoutes = (function () {
/**
* @param {?} routeReuseStrategy
* @param {?} futureState
* @param {?} currState
*/
function ActivateRoutes(routeReuseStrategy, futureState, currState) {
this.routeReuseStrategy = routeReuseStrategy;
this.futureState = futureState;
this.currState = currState;
}
/**
* @param {?} parentOutletMap
* @return {?}
*/
ActivateRoutes.prototype.activate = function (parentOutletMap) {
var /** @type {?} */ futureRoot = this.futureState._root;
var /** @type {?} */ currRoot = this.currState ? this.currState._root : null;
this.deactivateChildRoutes(futureRoot, currRoot, parentOutletMap);
advanceActivatedRoute(this.futureState.root);
this.activateChildRoutes(futureRoot, currRoot, parentOutletMap);
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} outletMap
* @return {?}
*/
ActivateRoutes.prototype.deactivateChildRoutes = function (futureNode, currNode, outletMap) {
var _this = this;
var /** @type {?} */ prevChildren = nodeChildrenAsMap(currNode);
futureNode.children.forEach(function (c) {
_this.deactivateRoutes(c, prevChildren[c.value.outlet], outletMap);
delete prevChildren[c.value.outlet];
});
forEach(prevChildren, function (v, k) { return _this.deactiveRouteAndItsChildren(v, outletMap); });
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} outletMap
* @return {?}
*/
ActivateRoutes.prototype.activateChildRoutes = function (futureNode, currNode, outletMap) {
var _this = this;
var /** @type {?} */ prevChildren = nodeChildrenAsMap(currNode);
futureNode.children.forEach(function (c) { _this.activateRoutes(c, prevChildren[c.value.outlet], outletMap); });
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentOutletMap
* @return {?}
*/
ActivateRoutes.prototype.deactivateRoutes = function (futureNode, currNode, parentOutletMap) {
var /** @type {?} */ future = futureNode.value;
var /** @type {?} */ curr = currNode ? currNode.value : null;
// reusing the node
if (future === curr) {
// If we have a normal route, we need to go through an outlet.
if (future.component) {
var /** @type {?} */ outlet = getOutlet(parentOutletMap, future);
this.deactivateChildRoutes(futureNode, currNode, outlet.outletMap);
}
else {
this.deactivateChildRoutes(futureNode, currNode, parentOutletMap);
}
}
else {
if (curr) {
this.deactiveRouteAndItsChildren(currNode, parentOutletMap);
}
}
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentOutletMap
* @return {?}
*/
ActivateRoutes.prototype.activateRoutes = function (futureNode, currNode, parentOutletMap) {
var /** @type {?} */ future = futureNode.value;
var /** @type {?} */ curr = currNode ? currNode.value : null;
// reusing the node
if (future === curr) {
// advance the route to push the parameters
advanceActivatedRoute(future);
// If we have a normal route, we need to go through an outlet.
if (future.component) {
var /** @type {?} */ outlet = getOutlet(parentOutletMap, future);
this.activateChildRoutes(futureNode, currNode, outlet.outletMap);
}
else {
this.activateChildRoutes(futureNode, currNode, parentOutletMap);
}
}
else {
// if we have a normal route, we need to advance the route
// and place the component into the outlet. After that recurse.
if (future.component) {
advanceActivatedRoute(future);
var /** @type {?} */ outlet = getOutlet(parentOutletMap, futureNode.value);
if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
var /** @type {?} */ stored = ((this.routeReuseStrategy.retrieve(future.snapshot)));
this.routeReuseStrategy.store(future.snapshot, null);
outlet.attach(stored.componentRef, stored.route.value);
advanceActivatedRouteNodeAndItsChildren(stored.route);
}
else {
var /** @type {?} */ outletMap = new RouterOutletMap();
this.placeComponentIntoOutlet(outletMap, future, outlet);
this.activateChildRoutes(futureNode, null, outletMap);
}
}
else {
advanceActivatedRoute(future);
this.activateChildRoutes(futureNode, null, parentOutletMap);
}
}
};
/**
* @param {?} outletMap
* @param {?} future
* @param {?} outlet
* @return {?}
*/
ActivateRoutes.prototype.placeComponentIntoOutlet = function (outletMap, future, outlet) {
var /** @type {?} */ config = parentLoadedConfig(future.snapshot);
var /** @type {?} */ cmpFactoryResolver = config ? config.module.componentFactoryResolver : null;
outlet.activateWith(future, cmpFactoryResolver, outletMap);
};
/**
* @param {?} route
* @param {?} parentOutletMap
* @return {?}
*/
ActivateRoutes.prototype.deactiveRouteAndItsChildren = function (route, parentOutletMap) {
if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
this.detachAndStoreRouteSubtree(route, parentOutletMap);
}
else {
this.deactiveRouteAndOutlet(route, parentOutletMap);
}
};
/**
* @param {?} route
* @param {?} parentOutletMap
* @return {?}
*/
ActivateRoutes.prototype.detachAndStoreRouteSubtree = function (route, parentOutletMap) {
var /** @type {?} */ outlet = getOutlet(parentOutletMap, route.value);
var /** @type {?} */ componentRef = outlet.detach();
this.routeReuseStrategy.store(route.value.snapshot, { componentRef: componentRef, route: route });
};
/**
* @param {?} route
* @param {?} parentOutletMap
* @return {?}
*/
ActivateRoutes.prototype.deactiveRouteAndOutlet = function (route, parentOutletMap) {
var _this = this;
var /** @type {?} */ prevChildren = nodeChildrenAsMap(route);
var /** @type {?} */ outlet = null;
// getOutlet throws when cannot find the right outlet,
// which can happen if an outlet was in an NgIf and was removed
try {
outlet = getOutlet(parentOutletMap, route.value);
}
catch (e) {
return;
}
var /** @type {?} */ childOutletMap = outlet.outletMap;
forEach(prevChildren, function (v, k) {
if (route.value.component) {
_this.deactiveRouteAndItsChildren(v, childOutletMap);
}
else {
_this.deactiveRouteAndItsChildren(v, parentOutletMap);
}
});
if (outlet && outlet.isActivated) {
outlet.deactivate();
}
};
return ActivateRoutes;
}());
/**
* @param {?} node
* @return {?}
*/
function advanceActivatedRouteNodeAndItsChildren(node) {
advanceActivatedRoute(node.value);
node.children.forEach(advanceActivatedRouteNodeAndItsChildren);
}
/**
* @param {?} snapshot
* @return {?}
*/
function parentLoadedConfig(snapshot) {
for (var /** @type {?} */ s = snapshot.parent; s; s = s.parent) {
var /** @type {?} */ route = s._routeConfig;
if (route && route._loadedConfig)
return route._loadedConfig;
if (route && route.component)
return null;
}
return null;
}
/**
* @param {?} snapshot
* @return {?}
*/
function closestLoadedConfig(snapshot) {
if (!snapshot)
return null;
for (var /** @type {?} */ s = snapshot.parent; s; s = s.parent) {
var /** @type {?} */ route = s._routeConfig;
if (route && route._loadedConfig)
return route._loadedConfig;
}
return null;
}
/**
* @template T
* @param {?} node
* @return {?}
*/
function nodeChildrenAsMap(node) {
var /** @type {?} */ map$$1 = {};
if (node) {
node.children.forEach(function (child) { return map$$1[child.value.outlet] = child; });
}
return map$$1;
}
/**
* @param {?} outletMap
* @param {?} route
* @return {?}
*/
function getOutlet(outletMap, route) {
var /** @type {?} */ outlet = outletMap._outlets[route.outlet];
if (!outlet) {
var /** @type {?} */ componentName = ((route.component)).name;
if (route.outlet === PRIMARY_OUTLET) {
throw new Error("Cannot find primary outlet to load '" + componentName + "'");
}
else {
throw new Error("Cannot find the outlet " + route.outlet + " to load '" + componentName + "'");
}
}
return outlet;
}
/**
* @param {?} commands
* @return {?}
*/
function validateCommands(commands) {
for (var /** @type {?} */ i = 0; i < commands.length; i++) {
var /** @type {?} */ cmd = commands[i];
if (cmd == null) {
throw new Error("The requested path contains " + cmd + " segment at index " + i);
}
}
}
/**
* @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
*/
/**
* \@whatItDoes Lets you link to specific parts of your app.
*
* \@howToUse
*
* Consider the following route configuration:
* `[{ path: 'user/:name', component: UserCmp }]`
*
* When linking to this `user/:name` route, you can write:
* `<a routerLink='/user/bob'>link to user component</a>`
*
* \@description
*
* The RouterLink directives let you link to specific parts of your app.
*
* When the link is static, you can use the directive as follows:
* `<a routerLink="/user/bob">link to user component</a>`
*
* If you use dynamic values to generate the link, you can pass an array of path
* segments, followed by the params for each segment.
*
* For instance `['/team', teamId, 'user', userName, {details: true}]`
* means that we want to generate a link to `/team/11/user/bob;details=true`.
*
* Multiple static segments can be merged into one
* (e.g., `['/team/11/user', userName, {details: true}]`).
*
* The first segment name can be prepended with `/`, `./`, or `../`:
* * If the first segment begins with `/`, the router will look up the route from the root of the
* app.
* * If the first segment begins with `./`, or doesn't begin with a slash, the router will
* instead look in the children of the current activated route.
* * And if the first segment begins with `../`, the router will go up one level.
*
* You can set query params and fragment as follows:
*
* ```
* <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
* link to user component
* </a>
* ```
* RouterLink will use these to generate this link: `/user/bob#education?debug=true`.
*
* (Deprecated in v4.0.0 use `queryParamsHandling` instead) You can also tell the
* directive to preserve the current query params and fragment:
*
* ```
* <a [routerLink]="['/user/bob']" preserveQueryParams preserveFragment>
* link to user component
* </a>
* ```
*
* You can tell the directive to how to handle queryParams, available options are:
* - 'merge' merge the queryParams into the current queryParams
* - 'preserve' prserve the current queryParams
* - default / '' use the queryParams only
* same options for {\@link NavigationExtras.queryParamsHandling}
*
* ```
* <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
* link to user component
* </a>
* ```
*
* The router link directive always treats the provided input as a delta to the current url.
*
* For instance, if the current url is `/user/(box//aux:team)`.
*
* Then the following link `<a [routerLink]="['/user/jim']">Jim</a>` will generate the link
* `/user/(jim//aux:team)`.
*
* \@ngModule RouterModule
*
* See {\@link Router.createUrlTree} for more information.
*
* \@stable
*/
var RouterLink = (function () {
/**
* @param {?} router
* @param {?} route
* @param {?} tabIndex
* @param {?} renderer
* @param {?} el
*/
function RouterLink(router, route, tabIndex, renderer, el) {
this.router = router;
this.route = route;
this.commands = [];
if (tabIndex == null) {
renderer.setElementAttribute(el.nativeElement, 'tabindex', '0');
}
}
Object.defineProperty(RouterLink.prototype, "routerLink", {
/**
* @param {?} commands
* @return {?}
*/
set: function (commands) {
if (commands != null) {
this.commands = Array.isArray(commands) ? commands : [commands];
}
else {
this.commands = [];
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(RouterLink.prototype, "preserveQueryParams", {
/**
* @deprecated 4.0.0 use `queryParamsHandling` instead.
* @param {?} value
* @return {?}
*/
set: function (value) {
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["E" /* isDevMode */])() && (console) && (console.warn)) {
console.warn('preserveQueryParams is deprecated!, use queryParamsHandling instead.');
}
this.preserve = value;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
RouterLink.prototype.onClick = function () {
var /** @type {?} */ extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
};
this.router.navigateByUrl(this.urlTree, extras);
return true;
};
Object.defineProperty(RouterLink.prototype, "urlTree", {
/**
* @return {?}
*/
get: function () {
return this.router.createUrlTree(this.commands, {
relativeTo: this.route,
queryParams: this.queryParams,
fragment: this.fragment,
preserveQueryParams: attrBoolValue(this.preserve),
queryParamsHandling: this.queryParamsHandling,
preserveFragment: attrBoolValue(this.preserveFragment),
});
},
enumerable: true,
configurable: true
});
return RouterLink;
}());
RouterLink.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["c" /* Directive */], args: [{ selector: ':not(a)[routerLink]' },] },
];
/**
* @nocollapse
*/
RouterLink.ctorParameters = function () { return [
{ type: Router, },
{ type: ActivatedRoute, },
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["Z" /* Attribute */], args: ['tabindex',] },] },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["i" /* ElementRef */], },
]; };
RouterLink.propDecorators = {
'queryParams': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'fragment': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'queryParamsHandling': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'preserveFragment': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'skipLocationChange': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'replaceUrl': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'routerLink': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'preserveQueryParams': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'onClick': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_6" /* HostListener */], args: ['click',] },],
};
/**
* \@whatItDoes Lets you link to specific parts of your app.
*
* See {\@link RouterLink} for more information.
*
* \@ngModule RouterModule
*
* \@stable
*/
var RouterLinkWithHref = (function () {
/**
* @param {?} router
* @param {?} route
* @param {?} locationStrategy
*/
function RouterLinkWithHref(router, route, locationStrategy) {
var _this = this;
this.router = router;
this.route = route;
this.locationStrategy = locationStrategy;
this.commands = [];
this.subscription = router.events.subscribe(function (s) {
if (s instanceof NavigationEnd) {
_this.updateTargetUrlAndHref();
}
});
}
Object.defineProperty(RouterLinkWithHref.prototype, "routerLink", {
/**
* @param {?} commands
* @return {?}
*/
set: function (commands) {
if (commands != null) {
this.commands = Array.isArray(commands) ? commands : [commands];
}
else {
this.commands = [];
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(RouterLinkWithHref.prototype, "preserveQueryParams", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["E" /* isDevMode */])() && (console) && (console.warn)) {
console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
}
this.preserve = value;
},
enumerable: true,
configurable: true
});
/**
* @param {?} changes
* @return {?}
*/
RouterLinkWithHref.prototype.ngOnChanges = function (changes) { this.updateTargetUrlAndHref(); };
/**
* @return {?}
*/
RouterLinkWithHref.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
/**
* @param {?} button
* @param {?} ctrlKey
* @param {?} metaKey
* @return {?}
*/
RouterLinkWithHref.prototype.onClick = function (button, ctrlKey, metaKey) {
if (button !== 0 || ctrlKey || metaKey) {
return true;
}
if (typeof this.target === 'string' && this.target != '_self') {
return true;
}
var /** @type {?} */ extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
};
this.router.navigateByUrl(this.urlTree, extras);
return false;
};
/**
* @return {?}
*/
RouterLinkWithHref.prototype.updateTargetUrlAndHref = function () {
this.href = this.locationStrategy.prepareExternalUrl(this.router.serializeUrl(this.urlTree));
};
Object.defineProperty(RouterLinkWithHref.prototype, "urlTree", {
/**
* @return {?}
*/
get: function () {
return this.router.createUrlTree(this.commands, {
relativeTo: this.route,
queryParams: this.queryParams,
fragment: this.fragment,
preserveQueryParams: attrBoolValue(this.preserve),
queryParamsHandling: this.queryParamsHandling,
preserveFragment: attrBoolValue(this.preserveFragment),
});
},
enumerable: true,
configurable: true
});
return RouterLinkWithHref;
}());
RouterLinkWithHref.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["c" /* Directive */], args: [{ selector: 'a[routerLink]' },] },
];
/**
* @nocollapse
*/
RouterLinkWithHref.ctorParameters = function () { return [
{ type: Router, },
{ type: ActivatedRoute, },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_common__["d" /* LocationStrategy */], },
]; };
RouterLinkWithHref.propDecorators = {
'target': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_7" /* HostBinding */], args: ['attr.target',] }, { type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'queryParams': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'fragment': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'queryParamsHandling': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'preserveFragment': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'skipLocationChange': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'replaceUrl': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'href': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_7" /* HostBinding */] },],
'routerLink': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'preserveQueryParams': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'onClick': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_6" /* HostListener */], args: ['click', ['$event.button', '$event.ctrlKey', '$event.metaKey'],] },],
};
/**
* @param {?} s
* @return {?}
*/
function attrBoolValue(s) {
return s === '' || !!s;
}
/**
* @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
*/
/**
* \@whatItDoes Lets you add a CSS class to an element when the link's route becomes active.
*
* \@howToUse
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
* ```
*
* \@description
*
* The RouterLinkActive directive lets you add a CSS class to an element when the link's route
* becomes active.
*
* Consider the following example:
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
* ```
*
* When the url is either '/user' or '/user/bob', the active-link class will
* be added to the `a` tag. If the url changes, the class will be removed.
*
* You can set more than one class, as follows:
*
* ```
* <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
* <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
* ```
*
* You can configure RouterLinkActive by passing `exact: true`. This will add the classes
* only when the url matches the link exactly.
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
* true}">Bob</a>
* ```
*
* You can assign the RouterLinkActive instance to a template variable and directly check
* the `isActive` status.
* ```
* <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
* Bob {{ rla.isActive ? '(already open)' : ''}}
* </a>
* ```
*
* Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink.
*
* ```
* <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
* <a routerLink="/user/jim">Jim</a>
* <a routerLink="/user/bob">Bob</a>
* </div>
* ```
*
* This will set the active-link class on the div tag if the url is either '/user/jim' or
* '/user/bob'.
*
* \@ngModule RouterModule
*
* \@stable
*/
var RouterLinkActive = (function () {
/**
* @param {?} router
* @param {?} element
* @param {?} renderer
* @param {?} cdr
*/
function RouterLinkActive(router, element, renderer, cdr) {
var _this = this;
this.router = router;
this.element = element;
this.renderer = renderer;
this.cdr = cdr;
this.classes = [];
this.active = false;
this.routerLinkActiveOptions = { exact: false };
this.subscription = router.events.subscribe(function (s) {
if (s instanceof NavigationEnd) {
_this.update();
}
});
}
Object.defineProperty(RouterLinkActive.prototype, "isActive", {
/**
* @return {?}
*/
get: function () { return this.active; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
RouterLinkActive.prototype.ngAfterContentInit = function () {
var _this = this;
this.links.changes.subscribe(function (_) { return _this.update(); });
this.linksWithHrefs.changes.subscribe(function (_) { return _this.update(); });
this.update();
};
Object.defineProperty(RouterLinkActive.prototype, "routerLinkActive", {
/**
* @param {?} data
* @return {?}
*/
set: function (data) {
var /** @type {?} */ classes = Array.isArray(data) ? data : data.split(' ');
this.classes = classes.filter(function (c) { return !!c; });
},
enumerable: true,
configurable: true
});
/**
* @param {?} changes
* @return {?}
*/
RouterLinkActive.prototype.ngOnChanges = function (changes) { this.update(); };
/**
* @return {?}
*/
RouterLinkActive.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
/**
* @return {?}
*/
RouterLinkActive.prototype.update = function () {
var _this = this;
if (!this.links || !this.linksWithHrefs || !this.router.navigated)
return;
var /** @type {?} */ hasActiveLinks = this.hasActiveLinks();
// react only when status has changed to prevent unnecessary dom updates
if (this.active !== hasActiveLinks) {
this.classes.forEach(function (c) { return _this.renderer.setElementClass(_this.element.nativeElement, c, hasActiveLinks); });
Promise.resolve(hasActiveLinks).then(function (active) { return _this.active = active; });
}
};
/**
* @param {?} router
* @return {?}
*/
RouterLinkActive.prototype.isLinkActive = function (router) {
var _this = this;
return function (link) { return router.isActive(link.urlTree, _this.routerLinkActiveOptions.exact); };
};
/**
* @return {?}
*/
RouterLinkActive.prototype.hasActiveLinks = function () {
return this.links.some(this.isLinkActive(this.router)) ||
this.linksWithHrefs.some(this.isLinkActive(this.router));
};
return RouterLinkActive;
}());
RouterLinkActive.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["c" /* Directive */], args: [{
selector: '[routerLinkActive]',
exportAs: 'routerLinkActive',
},] },
];
/**
* @nocollapse
*/
RouterLinkActive.ctorParameters = function () { return [
{ type: Router, },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["i" /* ElementRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_2" /* ChangeDetectorRef */], },
]; };
RouterLinkActive.propDecorators = {
'links': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_8" /* ContentChildren */], args: [RouterLink, { descendants: true },] },],
'linksWithHrefs': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_8" /* ContentChildren */], args: [RouterLinkWithHref, { descendants: true },] },],
'routerLinkActiveOptions': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
'routerLinkActive': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["n" /* Input */] },],
};
/**
* @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
*/
/**
* \@whatItDoes Acts as a placeholder that Angular dynamically fills based on the current router
* state.
*
* \@howToUse
*
* ```
* <router-outlet></router-outlet>
* <router-outlet name='left'></router-outlet>
* <router-outlet name='right'></router-outlet>
* ```
*
* A router outlet will emit an activate event any time a new component is being instantiated,
* and a deactivate event when it is being destroyed.
*
* ```
* <router-outlet
* (activate)='onActivate($event)'
* (deactivate)='onDeactivate($event)'></router-outlet>
* ```
* \@ngModule RouterModule
*
* \@stable
*/
var RouterOutlet = (function () {
/**
* @param {?} parentOutletMap
* @param {?} location
* @param {?} resolver
* @param {?} name
*/
function RouterOutlet(parentOutletMap, location, resolver, name) {
this.parentOutletMap = parentOutletMap;
this.location = location;
this.resolver = resolver;
this.name = name;
this.activateEvents = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["r" /* EventEmitter */]();
this.deactivateEvents = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["r" /* EventEmitter */]();
parentOutletMap.registerOutlet(name ? name : PRIMARY_OUTLET, this);
}
/**
* @return {?}
*/
RouterOutlet.prototype.ngOnDestroy = function () { this.parentOutletMap.removeOutlet(this.name ? this.name : PRIMARY_OUTLET); };
Object.defineProperty(RouterOutlet.prototype, "locationInjector", {
/**
* @deprecated since v4 *
* @return {?}
*/
get: function () { return this.location.injector; },
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "locationFactoryResolver", {
/**
* @deprecated since v4 *
* @return {?}
*/
get: function () { return this.resolver; },
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "isActivated", {
/**
* @return {?}
*/
get: function () { return !!this.activated; },
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "component", {
/**
* @return {?}
*/
get: function () {
if (!this.activated)
throw new Error('Outlet is not activated');
return this.activated.instance;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "activatedRoute", {
/**
* @return {?}
*/
get: function () {
if (!this.activated)
throw new Error('Outlet is not activated');
return this._activatedRoute;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
RouterOutlet.prototype.detach = function () {
if (!this.activated)
throw new Error('Outlet is not activated');
this.location.detach();
var /** @type {?} */ r = this.activated;
this.activated = ((null));
this._activatedRoute = ((null));
return r;
};
/**
* @param {?} ref
* @param {?} activatedRoute
* @return {?}
*/
RouterOutlet.prototype.attach = function (ref, activatedRoute) {
this.activated = ref;
this._activatedRoute = activatedRoute;
this.location.insert(ref.hostView);
};
/**
* @return {?}
*/
RouterOutlet.prototype.deactivate = function () {
if (this.activated) {
var /** @type {?} */ c = this.component;
this.activated.destroy();
this.activated = ((null));
this._activatedRoute = ((null));
this.deactivateEvents.emit(c);
}
};
/**
* @deprecated since v4, use {\@link #activateWith}
* @param {?} activatedRoute
* @param {?} resolver
* @param {?} injector
* @param {?} providers
* @param {?} outletMap
* @return {?}
*/
RouterOutlet.prototype.activate = function (activatedRoute, resolver, injector, providers, outletMap) {
if (this.isActivated) {
throw new Error('Cannot activate an already activated outlet');
}
this.outletMap = outletMap;
this._activatedRoute = activatedRoute;
var /** @type {?} */ snapshot = activatedRoute._futureSnapshot;
var /** @type {?} */ component = (((snapshot._routeConfig)).component);
var /** @type {?} */ factory = ((resolver.resolveComponentFactory(component)));
var /** @type {?} */ inj = __WEBPACK_IMPORTED_MODULE_1__angular_core__["_9" /* ReflectiveInjector */].fromResolvedProviders(providers, injector);
this.activated = this.location.createComponent(factory, this.location.length, inj, []);
this.activated.changeDetectorRef.detectChanges();
this.activateEvents.emit(this.activated.instance);
};
/**
* @param {?} activatedRoute
* @param {?} resolver
* @param {?} outletMap
* @return {?}
*/
RouterOutlet.prototype.activateWith = function (activatedRoute, resolver, outletMap) {
if (this.isActivated) {
throw new Error('Cannot activate an already activated outlet');
}
this.outletMap = outletMap;
this._activatedRoute = activatedRoute;
var /** @type {?} */ snapshot = activatedRoute._futureSnapshot;
var /** @type {?} */ component = (((snapshot._routeConfig)).component);
resolver = resolver || this.resolver;
var /** @type {?} */ factory = ((resolver.resolveComponentFactory(component)));
var /** @type {?} */ injector = new OutletInjector(activatedRoute, outletMap, this.location.injector);
this.activated = this.location.createComponent(factory, this.location.length, injector, []);
this.activated.changeDetectorRef.detectChanges();
this.activateEvents.emit(this.activated.instance);
};
return RouterOutlet;
}());
RouterOutlet.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["c" /* Directive */], args: [{ selector: 'router-outlet' },] },
];
/**
* @nocollapse
*/
RouterOutlet.ctorParameters = function () { return [
{ type: RouterOutletMap, },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["X" /* ViewContainerRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["W" /* ComponentFactoryResolver */], },
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["Z" /* Attribute */], args: ['name',] },] },
]; };
RouterOutlet.propDecorators = {
'activateEvents': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["t" /* Output */], args: ['activate',] },],
'deactivateEvents': [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["t" /* Output */], args: ['deactivate',] },],
};
var OutletInjector = (function () {
/**
* @param {?} route
* @param {?} map
* @param {?} parent
*/
function OutletInjector(route, map$$1, parent) {
this.route = route;
this.map = map$$1;
this.parent = parent;
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
OutletInjector.prototype.get = function (token, notFoundValue) {
if (token === ActivatedRoute) {
return this.route;
}
if (token === RouterOutletMap) {
return this.map;
}
return this.parent.get(token, notFoundValue);
};
return OutletInjector;
}());
/**
* @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
*/
/**
* \@whatItDoes Provides a way to customize when activated routes get reused.
*
* \@experimental
* @abstract
*/
var RouteReuseStrategy = (function () {
function RouteReuseStrategy() {
}
/**
* Determines if this route (and its subtree) should be detached to be reused later
* @abstract
* @param {?} route
* @return {?}
*/
RouteReuseStrategy.prototype.shouldDetach = function (route) { };
/**
* Stores the detached route
* @abstract
* @param {?} route
* @param {?} handle
* @return {?}
*/
RouteReuseStrategy.prototype.store = function (route, handle) { };
/**
* Determines if this route (and its subtree) should be reattached
* @abstract
* @param {?} route
* @return {?}
*/
RouteReuseStrategy.prototype.shouldAttach = function (route) { };
/**
* Retrieves the previously stored route
* @abstract
* @param {?} route
* @return {?}
*/
RouteReuseStrategy.prototype.retrieve = function (route) { };
/**
* Determines if a route should be reused
* @abstract
* @param {?} future
* @param {?} curr
* @return {?}
*/
RouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) { };
return RouteReuseStrategy;
}());
/**
*@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
*/
/**
* \@whatItDoes Provides a preloading strategy.
*
* \@experimental
* @abstract
*/
var PreloadingStrategy = (function () {
function PreloadingStrategy() {
}
/**
* @abstract
* @param {?} route
* @param {?} fn
* @return {?}
*/
PreloadingStrategy.prototype.preload = function (route, fn) { };
return PreloadingStrategy;
}());
/**
* \@whatItDoes Provides a preloading strategy that preloads all modules as quickly as possible.
*
* \@howToUse
*
* ```
* RouteModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
* ```
*
* \@experimental
*/
var PreloadAllModules = (function () {
function PreloadAllModules() {
}
/**
* @param {?} route
* @param {?} fn
* @return {?}
*/
PreloadAllModules.prototype.preload = function (route, fn) {
return __WEBPACK_IMPORTED_MODULE_13_rxjs_operator_catch__["_catch"].call(fn(), function () { return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(null); });
};
return PreloadAllModules;
}());
/**
* \@whatItDoes Provides a preloading strategy that does not preload any modules.
*
* \@description
*
* This strategy is enabled by default.
*
* \@experimental
*/
var NoPreloading = (function () {
function NoPreloading() {
}
/**
* @param {?} route
* @param {?} fn
* @return {?}
*/
NoPreloading.prototype.preload = function (route, fn) { return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(null); };
return NoPreloading;
}());
/**
* The preloader optimistically loads all router configurations to
* make navigations into lazily-loaded sections of the application faster.
*
* The preloader runs in the background. When the router bootstraps, the preloader
* starts listening to all navigation events. After every such event, the preloader
* will check if any configurations can be loaded lazily.
*
* If a route is protected by `canLoad` guards, the preloaded will not load it.
*
* \@stable
*/
var RouterPreloader = (function () {
/**
* @param {?} router
* @param {?} moduleLoader
* @param {?} compiler
* @param {?} injector
* @param {?} preloadingStrategy
*/
function RouterPreloader(router, moduleLoader, compiler, injector, preloadingStrategy) {
this.router = router;
this.injector = injector;
this.preloadingStrategy = preloadingStrategy;
var onStartLoad = function (r) { return router.triggerEvent(new RouteConfigLoadStart(r)); };
var onEndLoad = function (r) { return router.triggerEvent(new RouteConfigLoadEnd(r)); };
this.loader = new RouterConfigLoader(moduleLoader, compiler, onStartLoad, onEndLoad);
}
;
/**
* @return {?}
*/
RouterPreloader.prototype.setUpPreloading = function () {
var _this = this;
var /** @type {?} */ navigations$ = __WEBPACK_IMPORTED_MODULE_20_rxjs_operator_filter__["filter"].call(this.router.events, function (e) { return e instanceof NavigationEnd; });
this.subscription = __WEBPACK_IMPORTED_MODULE_6_rxjs_operator_concatMap__["concatMap"].call(navigations$, function () { return _this.preload(); }).subscribe(function () { });
};
/**
* @return {?}
*/
RouterPreloader.prototype.preload = function () {
var /** @type {?} */ ngModule = this.injector.get(__WEBPACK_IMPORTED_MODULE_1__angular_core__["V" /* NgModuleRef */]);
return this.processRoutes(ngModule, this.router.config);
};
/**
* @return {?}
*/
RouterPreloader.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
/**
* @param {?} ngModule
* @param {?} routes
* @return {?}
*/
RouterPreloader.prototype.processRoutes = function (ngModule, routes) {
var /** @type {?} */ res = [];
for (var _i = 0, routes_5 = routes; _i < routes_5.length; _i++) {
var route = routes_5[_i];
// we already have the config loaded, just recurse
if (route.loadChildren && !route.canLoad && route._loadedConfig) {
var /** @type {?} */ childConfig = route._loadedConfig;
res.push(this.processRoutes(childConfig.module, childConfig.routes));
}
else if (route.loadChildren && !route.canLoad) {
res.push(this.preloadConfig(ngModule, route));
}
else if (route.children) {
res.push(this.processRoutes(ngModule, route.children));
}
}
return __WEBPACK_IMPORTED_MODULE_18_rxjs_operator_mergeAll__["mergeAll"].call(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4_rxjs_observable_from__["from"])(res));
};
/**
* @param {?} ngModule
* @param {?} route
* @return {?}
*/
RouterPreloader.prototype.preloadConfig = function (ngModule, route) {
var _this = this;
return this.preloadingStrategy.preload(route, function () {
var /** @type {?} */ loaded$ = _this.loader.load(ngModule.injector, route);
return __WEBPACK_IMPORTED_MODULE_10_rxjs_operator_mergeMap__["mergeMap"].call(loaded$, function (config) {
route._loadedConfig = config;
return _this.processRoutes(config.module, config.routes);
});
});
};
return RouterPreloader;
}());
RouterPreloader.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
RouterPreloader.ctorParameters = function () { return [
{ type: Router, },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_10" /* NgModuleFactoryLoader */], },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_11" /* Compiler */], },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["m" /* Injector */], },
{ type: PreloadingStrategy, },
]; };
/**
* @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
*/
/**
* \@whatItDoes Contains a list of directives
* \@stable
*/
var ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];
/**
* \@whatItDoes Is used in DI to configure the router.
* \@stable
*/
var ROUTER_CONFIGURATION = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["e" /* InjectionToken */]('ROUTER_CONFIGURATION');
/**
* \@docsNotRequired
*/
var ROUTER_FORROOT_GUARD = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["e" /* InjectionToken */]('ROUTER_FORROOT_GUARD');
var ROUTER_PROVIDERS = [
__WEBPACK_IMPORTED_MODULE_0__angular_common__["e" /* Location */],
{ provide: UrlSerializer, useClass: DefaultUrlSerializer },
{
provide: Router,
useFactory: setupRouter,
deps: [
__WEBPACK_IMPORTED_MODULE_1__angular_core__["y" /* ApplicationRef */], UrlSerializer, RouterOutletMap, __WEBPACK_IMPORTED_MODULE_0__angular_common__["e" /* Location */], __WEBPACK_IMPORTED_MODULE_1__angular_core__["m" /* Injector */], __WEBPACK_IMPORTED_MODULE_1__angular_core__["_10" /* NgModuleFactoryLoader */],
__WEBPACK_IMPORTED_MODULE_1__angular_core__["_11" /* Compiler */], ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */]()],
[RouteReuseStrategy, new __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */]()]
]
},
RouterOutletMap,
{ provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] },
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_10" /* NgModuleFactoryLoader */], useClass: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_12" /* SystemJsNgModuleLoader */] },
RouterPreloader,
NoPreloading,
PreloadAllModules,
{ provide: ROUTER_CONFIGURATION, useValue: { enableTracing: false } },
];
/**
* @return {?}
*/
function routerNgProbeToken() {
return new __WEBPACK_IMPORTED_MODULE_1__angular_core__["B" /* NgProbeToken */]('Router', Router);
}
/**
* \@whatItDoes Adds router directives and providers.
*
* \@howToUse
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* \@NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* \@NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* \@description
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
* overview of how the router should be used.
*
* \@stable
*/
var RouterModule = (function () {
/**
* @param {?} guard
* @param {?} router
*/
function RouterModule(guard, router) {
}
/**
* Creates a module with all the router providers and directives. It also optionally sets up an
* application listener to perform an initial navigation.
*
* Options:
* * `enableTracing` makes the router log all its internal events to the console.
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
* API.
* * `initialNavigation` disables the initial navigation.
* * `errorHandler` provides a custom error handler.
* @param {?} routes
* @param {?=} config
* @return {?}
*/
RouterModule.forRoot = function (routes, config) {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
provideRoutes(routes),
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */](), new __WEBPACK_IMPORTED_MODULE_1__angular_core__["s" /* SkipSelf */]()]]
},
{ provide: ROUTER_CONFIGURATION, useValue: config ? config : {} },
{
provide: __WEBPACK_IMPORTED_MODULE_0__angular_common__["d" /* LocationStrategy */],
useFactory: provideLocationStrategy,
deps: [
__WEBPACK_IMPORTED_MODULE_0__angular_common__["a" /* PlatformLocation */], [new __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */](__WEBPACK_IMPORTED_MODULE_0__angular_common__["f" /* APP_BASE_HREF */]), new __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */]()], ROUTER_CONFIGURATION
]
},
{
provide: PreloadingStrategy,
useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
NoPreloading
},
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["B" /* NgProbeToken */], multi: true, useFactory: routerNgProbeToken },
provideRouterInitializer(),
],
};
};
/**
* Creates a module with all the router directives and a provider registering routes.
* @param {?} routes
* @return {?}
*/
RouterModule.forChild = function (routes) {
return { ngModule: RouterModule, providers: [provideRoutes(routes)] };
};
return RouterModule;
}());
RouterModule.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["b" /* NgModule */], args: [{ declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES },] },
];
/**
* @nocollapse
*/
RouterModule.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [ROUTER_FORROOT_GUARD,] },] },
{ type: Router, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */] },] },
]; };
/**
* @param {?} platformLocationStrategy
* @param {?} baseHref
* @param {?=} options
* @return {?}
*/
function provideLocationStrategy(platformLocationStrategy, baseHref, options) {
if (options === void 0) { options = {}; }
return options.useHash ? new __WEBPACK_IMPORTED_MODULE_0__angular_common__["g" /* HashLocationStrategy */](platformLocationStrategy, baseHref) :
new __WEBPACK_IMPORTED_MODULE_0__angular_common__["h" /* PathLocationStrategy */](platformLocationStrategy, baseHref);
}
/**
* @param {?} router
* @return {?}
*/
function provideForRootGuard(router) {
if (router) {
throw new Error("RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.");
}
return 'guarded';
}
/**
* \@whatItDoes Registers routes.
*
* \@howToUse
*
* ```
* \@NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* \@stable
* @param {?} routes
* @return {?}
*/
function provideRoutes(routes) {
return [
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_13" /* ANALYZE_FOR_ENTRY_COMPONENTS */], multi: true, useValue: routes },
{ provide: ROUTES, multi: true, useValue: routes },
];
}
/**
* @param {?} ref
* @param {?} urlSerializer
* @param {?} outletMap
* @param {?} location
* @param {?} injector
* @param {?} loader
* @param {?} compiler
* @param {?} config
* @param {?=} opts
* @param {?=} urlHandlingStrategy
* @param {?=} routeReuseStrategy
* @return {?}
*/
function setupRouter(ref, urlSerializer, outletMap, location, injector, loader, compiler, config, opts, urlHandlingStrategy, routeReuseStrategy) {
if (opts === void 0) { opts = {}; }
var /** @type {?} */ router = new Router(null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(config));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
if (routeReuseStrategy) {
router.routeReuseStrategy = routeReuseStrategy;
}
if (opts.errorHandler) {
router.errorHandler = opts.errorHandler;
}
if (opts.enableTracing) {
var /** @type {?} */ dom_1 = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_19__angular_platform_browser__["c" /* ɵgetDOM */])();
router.events.subscribe(function (e) {
dom_1.logGroup("Router Event: " + ((e.constructor)).name);
dom_1.log(e.toString());
dom_1.log(e);
dom_1.logGroupEnd();
});
}
return router;
}
/**
* @param {?} router
* @return {?}
*/
function rootRoute(router) {
return router.routerState.root;
}
/**
* To initialize the router properly we need to do in two steps:
*
* We need to start the navigation in a APP_INITIALIZER to block the bootstrap if
* a resolver or a guards executes asynchronously. Second, we need to actually run
* activation in a BOOTSTRAP_LISTENER. We utilize the afterPreactivation
* hook provided by the router to do that.
*
* The router navigation starts, reaches the point when preactivation is done, and then
* pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener.
*/
var RouterInitializer = (function () {
/**
* @param {?} injector
*/
function RouterInitializer(injector) {
this.injector = injector;
this.initNavigation = false;
this.resultOfPreactivationDone = new __WEBPACK_IMPORTED_MODULE_3_rxjs_Subject__["Subject"]();
}
/**
* @return {?}
*/
RouterInitializer.prototype.appInitializer = function () {
var _this = this;
var /** @type {?} */ p = this.injector.get(__WEBPACK_IMPORTED_MODULE_0__angular_common__["i" /* LOCATION_INITIALIZED */], Promise.resolve(null));
return p.then(function () {
var /** @type {?} */ resolve = ((null));
var /** @type {?} */ res = new Promise(function (r) { return resolve = r; });
var /** @type {?} */ router = _this.injector.get(Router);
var /** @type {?} */ opts = _this.injector.get(ROUTER_CONFIGURATION);
if (_this.isLegacyDisabled(opts) || _this.isLegacyEnabled(opts)) {
resolve(true);
}
else if (opts.initialNavigation === 'disabled') {
router.setUpLocationChangeListener();
resolve(true);
}
else if (opts.initialNavigation === 'enabled') {
router.hooks.afterPreactivation = function () {
// only the initial navigation should be delayed
if (!_this.initNavigation) {
_this.initNavigation = true;
resolve(true);
return _this.resultOfPreactivationDone;
}
else {
return (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5_rxjs_observable_of__["of"])(null));
}
};
router.initialNavigation();
}
else {
throw new Error("Invalid initialNavigation options: '" + opts.initialNavigation + "'");
}
return res;
});
};
/**
* @param {?} bootstrappedComponentRef
* @return {?}
*/
RouterInitializer.prototype.bootstrapListener = function (bootstrappedComponentRef) {
var /** @type {?} */ opts = this.injector.get(ROUTER_CONFIGURATION);
var /** @type {?} */ preloader = this.injector.get(RouterPreloader);
var /** @type {?} */ router = this.injector.get(Router);
var /** @type {?} */ ref = this.injector.get(__WEBPACK_IMPORTED_MODULE_1__angular_core__["y" /* ApplicationRef */]);
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
if (this.isLegacyEnabled(opts)) {
router.initialNavigation();
}
else if (this.isLegacyDisabled(opts)) {
router.setUpLocationChangeListener();
}
preloader.setUpPreloading();
router.resetRootComponentType(ref.componentTypes[0]);
this.resultOfPreactivationDone.next(/** @type {?} */ ((null)));
this.resultOfPreactivationDone.complete();
};
/**
* @param {?} opts
* @return {?}
*/
RouterInitializer.prototype.isLegacyEnabled = function (opts) {
return opts.initialNavigation === 'legacy_enabled' || opts.initialNavigation === true ||
opts.initialNavigation === undefined;
};
/**
* @param {?} opts
* @return {?}
*/
RouterInitializer.prototype.isLegacyDisabled = function (opts) {
return opts.initialNavigation === 'legacy_disabled' || opts.initialNavigation === false;
};
return RouterInitializer;
}());
RouterInitializer.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
RouterInitializer.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["m" /* Injector */], },
]; };
/**
* @param {?} r
* @return {?}
*/
function getAppInitializer(r) {
return r.appInitializer.bind(r);
}
/**
* @param {?} r
* @return {?}
*/
function getBootstrapListener(r) {
return r.bootstrapListener.bind(r);
}
/**
* A token for the router initializer that will be called after the app is bootstrapped.
*
* \@experimental
*/
var ROUTER_INITIALIZER = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["e" /* InjectionToken */]('Router Initializer');
/**
* @return {?}
*/
function provideRouterInitializer() {
return [
RouterInitializer,
{
provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["w" /* APP_INITIALIZER */],
multi: true,
useFactory: getAppInitializer,
deps: [RouterInitializer]
},
{ provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer] },
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_14" /* APP_BOOTSTRAP_LISTENER */], multi: true, useExisting: ROUTER_INITIALIZER },
];
}
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
var VERSION = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["u" /* Version */]('4.1.1');
/**
* @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
*/
/**
* @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
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the router package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=router.es5.js.map
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var isFunction_1 = __webpack_require__(83);
var Subscription_1 = __webpack_require__(26);
var Observer_1 = __webpack_require__(103);
var rxSubscriber_1 = __webpack_require__(81);
/**
* Implements the {@link Observer} interface and extends the
* {@link Subscription} class. While the {@link Observer} is the public API for
* consuming the values of an {@link Observable}, all Observers get converted to
* a Subscriber, in order to provide Subscription-like capabilities such as
* `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
* implementing operators, but it is rarely used as a public API.
*
* @class Subscriber<T>
*/
var Subscriber = (function (_super) {
__extends(Subscriber, _super);
/**
* @param {Observer|function(value: T): void} [destinationOrNext] A partially
* defined Observer or a `next` callback function.
* @param {function(e: ?any): void} [error] The `error` callback of an
* Observer.
* @param {function(): void} [complete] The `complete` callback of an
* Observer.
*/
function Subscriber(destinationOrNext, error, complete) {
_super.call(this);
this.syncErrorValue = null;
this.syncErrorThrown = false;
this.syncErrorThrowable = false;
this.isStopped = false;
switch (arguments.length) {
case 0:
this.destination = Observer_1.empty;
break;
case 1:
if (!destinationOrNext) {
this.destination = Observer_1.empty;
break;
}
if (typeof destinationOrNext === 'object') {
if (destinationOrNext instanceof Subscriber) {
this.destination = destinationOrNext;
this.destination.add(this);
}
else {
this.syncErrorThrowable = true;
this.destination = new SafeSubscriber(this, destinationOrNext);
}
break;
}
default:
this.syncErrorThrowable = true;
this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
break;
}
}
Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
/**
* A static factory for a Subscriber, given a (potentially partial) definition
* of an Observer.
* @param {function(x: ?T): void} [next] The `next` callback of an Observer.
* @param {function(e: ?any): void} [error] The `error` callback of an
* Observer.
* @param {function(): void} [complete] The `complete` callback of an
* Observer.
* @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
* Observer represented by the given arguments.
*/
Subscriber.create = function (next, error, complete) {
var subscriber = new Subscriber(next, error, complete);
subscriber.syncErrorThrowable = false;
return subscriber;
};
/**
* The {@link Observer} callback to receive notifications of type `next` from
* the Observable, with a value. The Observable may call this method 0 or more
* times.
* @param {T} [value] The `next` value.
* @return {void}
*/
Subscriber.prototype.next = function (value) {
if (!this.isStopped) {
this._next(value);
}
};
/**
* The {@link Observer} callback to receive notifications of type `error` from
* the Observable, with an attached {@link Error}. Notifies the Observer that
* the Observable has experienced an error condition.
* @param {any} [err] The `error` exception.
* @return {void}
*/
Subscriber.prototype.error = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this._error(err);
}
};
/**
* The {@link Observer} callback to receive a valueless notification of type
* `complete` from the Observable. Notifies the Observer that the Observable
* has finished sending push-based notifications.
* @return {void}
*/
Subscriber.prototype.complete = function () {
if (!this.isStopped) {
this.isStopped = true;
this._complete();
}
};
Subscriber.prototype.unsubscribe = function () {
if (this.closed) {
return;
}
this.isStopped = true;
_super.prototype.unsubscribe.call(this);
};
Subscriber.prototype._next = function (value) {
this.destination.next(value);
};
Subscriber.prototype._error = function (err) {
this.destination.error(err);
this.unsubscribe();
};
Subscriber.prototype._complete = function () {
this.destination.complete();
this.unsubscribe();
};
Subscriber.prototype._unsubscribeAndRecycle = function () {
var _a = this, _parent = _a._parent, _parents = _a._parents;
this._parent = null;
this._parents = null;
this.unsubscribe();
this.closed = false;
this.isStopped = false;
this._parent = _parent;
this._parents = _parents;
return this;
};
return Subscriber;
}(Subscription_1.Subscription));
exports.Subscriber = Subscriber;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var SafeSubscriber = (function (_super) {
__extends(SafeSubscriber, _super);
function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
_super.call(this);
this._parentSubscriber = _parentSubscriber;
var next;
var context = this;
if (isFunction_1.isFunction(observerOrNext)) {
next = observerOrNext;
}
else if (observerOrNext) {
next = observerOrNext.next;
error = observerOrNext.error;
complete = observerOrNext.complete;
if (observerOrNext !== Observer_1.empty) {
context = Object.create(observerOrNext);
if (isFunction_1.isFunction(context.unsubscribe)) {
this.add(context.unsubscribe.bind(context));
}
context.unsubscribe = this.unsubscribe.bind(this);
}
}
this._context = context;
this._next = next;
this._error = error;
this._complete = complete;
}
SafeSubscriber.prototype.next = function (value) {
if (!this.isStopped && this._next) {
var _parentSubscriber = this._parentSubscriber;
if (!_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(this._next, value);
}
else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
this.unsubscribe();
}
}
};
SafeSubscriber.prototype.error = function (err) {
if (!this.isStopped) {
var _parentSubscriber = this._parentSubscriber;
if (this._error) {
if (!_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(this._error, err);
this.unsubscribe();
}
else {
this.__tryOrSetError(_parentSubscriber, this._error, err);
this.unsubscribe();
}
}
else if (!_parentSubscriber.syncErrorThrowable) {
this.unsubscribe();
throw err;
}
else {
_parentSubscriber.syncErrorValue = err;
_parentSubscriber.syncErrorThrown = true;
this.unsubscribe();
}
}
};
SafeSubscriber.prototype.complete = function () {
if (!this.isStopped) {
var _parentSubscriber = this._parentSubscriber;
if (this._complete) {
if (!_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(this._complete);
this.unsubscribe();
}
else {
this.__tryOrSetError(_parentSubscriber, this._complete);
this.unsubscribe();
}
}
else {
this.unsubscribe();
}
}
};
SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
try {
fn.call(this._context, value);
}
catch (err) {
this.unsubscribe();
throw err;
}
};
SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
try {
fn.call(this._context, value);
}
catch (err) {
parent.syncErrorValue = err;
parent.syncErrorThrown = true;
return true;
}
return false;
};
SafeSubscriber.prototype._unsubscribe = function () {
var _parentSubscriber = this._parentSubscriber;
this._context = null;
this._parentSubscriber = null;
_parentSubscriber.unsubscribe();
};
return SafeSubscriber;
}(Subscriber));
//# sourceMappingURL=Subscriber.js.map
/***/ }),
/* 6 */,
/* 7 */,
/* 8 */,
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_rxjs_observable_forkJoin__ = __webpack_require__(296);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_rxjs_observable_forkJoin___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_rxjs_observable_forkJoin__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_rxjs_observable_fromPromise__ = __webpack_require__(108);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_rxjs_observable_fromPromise___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_rxjs_observable_fromPromise__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_rxjs_operator_map__ = __webpack_require__(76);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_rxjs_operator_map___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_rxjs_operator_map__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__angular_platform_browser__ = __webpack_require__(22);
/* unused harmony export AbstractControlDirective */
/* unused harmony export AbstractFormGroupDirective */
/* unused harmony export CheckboxControlValueAccessor */
/* unused harmony export ControlContainer */
/* unused harmony export NG_VALUE_ACCESSOR */
/* unused harmony export COMPOSITION_BUFFER_MODE */
/* unused harmony export DefaultValueAccessor */
/* unused harmony export NgControl */
/* unused harmony export NgControlStatus */
/* unused harmony export NgControlStatusGroup */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return NgForm; });
/* unused harmony export NgModel */
/* unused harmony export NgModelGroup */
/* unused harmony export RadioControlValueAccessor */
/* unused harmony export FormControlDirective */
/* unused harmony export FormControlName */
/* unused harmony export FormGroupDirective */
/* unused harmony export FormArrayName */
/* unused harmony export FormGroupName */
/* unused harmony export NgSelectOption */
/* unused harmony export SelectControlValueAccessor */
/* unused harmony export SelectMultipleControlValueAccessor */
/* unused harmony export CheckboxRequiredValidator */
/* unused harmony export EmailValidator */
/* unused harmony export MaxLengthValidator */
/* unused harmony export MinLengthValidator */
/* unused harmony export PatternValidator */
/* unused harmony export RequiredValidator */
/* unused harmony export FormBuilder */
/* unused harmony export AbstractControl */
/* unused harmony export FormArray */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return FormControl; });
/* unused harmony export FormGroup */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return NG_ASYNC_VALIDATORS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return NG_VALIDATORS; });
/* unused harmony export Validators */
/* unused harmony export VERSION */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FormsModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ReactiveFormsModule; });
/* unused harmony export ɵba */
/* unused harmony export ɵz */
/* unused harmony export ɵx */
/* unused harmony export ɵy */
/* unused harmony export ɵa */
/* unused harmony export ɵb */
/* unused harmony export ɵc */
/* unused harmony export ɵd */
/* unused harmony export ɵe */
/* unused harmony export ɵf */
/* unused harmony export ɵg */
/* unused harmony export ɵbf */
/* unused harmony export ɵbb */
/* unused harmony export ɵbc */
/* unused harmony export ɵh */
/* unused harmony export ɵi */
/* unused harmony export ɵbd */
/* unused harmony export ɵbe */
/* unused harmony export ɵj */
/* unused harmony export ɵk */
/* unused harmony export ɵl */
/* unused harmony export ɵn */
/* unused harmony export ɵm */
/* unused harmony export ɵo */
/* unused harmony export ɵq */
/* unused harmony export ɵp */
/* unused harmony export ɵs */
/* unused harmony export ɵt */
/* unused harmony export ɵv */
/* unused harmony export ɵu */
/* unused harmony export ɵw */
/* unused harmony export ɵr */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.1
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @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
*/
/**
* Base class for control directives.
*
* Only used internally in the forms module.
*
* \@stable
* @abstract
*/
var AbstractControlDirective = (function () {
function AbstractControlDirective() {
}
/**
* @abstract
* @return {?}
*/
AbstractControlDirective.prototype.control = function () { };
Object.defineProperty(AbstractControlDirective.prototype, "value", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.value : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "valid", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.valid : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "invalid", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.invalid : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "pending", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.pending : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "errors", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.errors : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "pristine", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.pristine : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "dirty", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.dirty : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "touched", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.touched : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "untouched", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.untouched : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "disabled", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.disabled : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "enabled", {
/**
* @return {?}
*/
get: function () { return this.control ? this.control.enabled : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "statusChanges", {
/**
* @return {?}
*/
get: function () {
return this.control ? this.control.statusChanges : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "valueChanges", {
/**
* @return {?}
*/
get: function () {
return this.control ? this.control.valueChanges : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "path", {
/**
* @return {?}
*/
get: function () { return null; },
enumerable: true,
configurable: true
});
/**
* @param {?=} value
* @return {?}
*/
AbstractControlDirective.prototype.reset = function (value) {
if (value === void 0) { value = undefined; }
if (this.control)
this.control.reset(value);
};
/**
* @param {?} errorCode
* @param {?=} path
* @return {?}
*/
AbstractControlDirective.prototype.hasError = function (errorCode, path) {
return this.control ? this.control.hasError(errorCode, path) : false;
};
/**
* @param {?} errorCode
* @param {?=} path
* @return {?}
*/
AbstractControlDirective.prototype.getError = function (errorCode, path) {
return this.control ? this.control.getError(errorCode, path) : null;
};
return AbstractControlDirective;
}());
/**
* @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
*/
/**
* A directive that contains multiple {\@link NgControl}s.
*
* Only used by the forms module.
*
* \@stable
* @abstract
*/
var ControlContainer = (function (_super) {
__extends(ControlContainer, _super);
function ControlContainer() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(ControlContainer.prototype, "formDirective", {
/**
* Get the form to which this container belongs.
* @return {?}
*/
get: function () { return null; },
enumerable: true,
configurable: true
});
Object.defineProperty(ControlContainer.prototype, "path", {
/**
* Get the path to this container.
* @return {?}
*/
get: function () { return null; },
enumerable: true,
configurable: true
});
return ControlContainer;
}(AbstractControlDirective));
/**
* @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
*/
var __assign = (undefined && undefined.__assign) || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
/**
* @param {?} value
* @return {?}
*/
function isEmptyInputValue(value) {
// we don't check for string here so it also works with arrays
return value == null || value.length === 0;
}
/**
* Providers for validators to be used for {\@link FormControl}s in a form.
*
* Provide this using `multi: true` to add validators.
*
* \@stable
*/
var NG_VALIDATORS = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('NgValidators');
/**
* Providers for asynchronous validators to be used for {\@link FormControl}s
* in a form.
*
* Provide this using `multi: true` to add validators.
*
* See {\@link NG_VALIDATORS} for more details.
*
* \@stable
*/
var NG_ASYNC_VALIDATORS = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('NgAsyncValidators');
var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
/**
* Provides a set of validators used by form controls.
*
* A validator is a function that processes a {\@link FormControl} or collection of
* controls and returns a map of errors. A null map means that validation has passed.
*
* ### Example
*
* ```typescript
* var loginControl = new FormControl("", Validators.required)
* ```
*
* \@stable
*/
var Validators = (function () {
function Validators() {
}
/**
* Validator that requires controls to have a non-empty value.
* @param {?} control
* @return {?}
*/
Validators.required = function (control) {
return isEmptyInputValue(control.value) ? { 'required': true } : null;
};
/**
* Validator that requires control value to be true.
* @param {?} control
* @return {?}
*/
Validators.requiredTrue = function (control) {
return control.value === true ? null : { 'required': true };
};
/**
* Validator that performs email validation.
* @param {?} control
* @return {?}
*/
Validators.email = function (control) {
return EMAIL_REGEXP.test(control.value) ? null : { 'email': true };
};
/**
* Validator that requires controls to have a value of a minimum length.
* @param {?} minLength
* @return {?}
*/
Validators.minLength = function (minLength) {
return function (control) {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
var /** @type {?} */ length = control.value ? control.value.length : 0;
return length < minLength ?
{ 'minlength': { 'requiredLength': minLength, 'actualLength': length } } :
null;
};
};
/**
* Validator that requires controls to have a value of a maximum length.
* @param {?} maxLength
* @return {?}
*/
Validators.maxLength = function (maxLength) {
return function (control) {
var /** @type {?} */ length = control.value ? control.value.length : 0;
return length > maxLength ?
{ 'maxlength': { 'requiredLength': maxLength, 'actualLength': length } } :
null;
};
};
/**
* Validator that requires a control to match a regex to its value.
* @param {?} pattern
* @return {?}
*/
Validators.pattern = function (pattern) {
if (!pattern)
return Validators.nullValidator;
var /** @type {?} */ regex;
var /** @type {?} */ regexStr;
if (typeof pattern === 'string') {
regexStr = "^" + pattern + "$";
regex = new RegExp(regexStr);
}
else {
regexStr = pattern.toString();
regex = pattern;
}
return function (control) {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
var /** @type {?} */ value = control.value;
return regex.test(value) ? null :
{ 'pattern': { 'requiredPattern': regexStr, 'actualValue': value } };
};
};
/**
* No-op validator.
* @param {?} c
* @return {?}
*/
Validators.nullValidator = function (c) { return null; };
/**
* @param {?} validators
* @return {?}
*/
Validators.compose = function (validators) {
if (!validators)
return null;
var /** @type {?} */ presentValidators = (validators.filter(isPresent));
if (presentValidators.length == 0)
return null;
return function (control) {
return _mergeErrors(_executeValidators(control, presentValidators));
};
};
/**
* @param {?} validators
* @return {?}
*/
Validators.composeAsync = function (validators) {
if (!validators)
return null;
var /** @type {?} */ presentValidators = (validators.filter(isPresent));
if (presentValidators.length == 0)
return null;
return function (control) {
var /** @type {?} */ observables = _executeAsyncValidators(control, presentValidators).map(toObservable);
return __WEBPACK_IMPORTED_MODULE_3_rxjs_operator_map__["map"].call(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_rxjs_observable_forkJoin__["forkJoin"])(observables), _mergeErrors);
};
};
return Validators;
}());
/**
* @param {?} o
* @return {?}
*/
function isPresent(o) {
return o != null;
}
/**
* @param {?} r
* @return {?}
*/
function toObservable(r) {
var /** @type {?} */ obs = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["f" /* ɵisPromise */])(r) ? __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_rxjs_observable_fromPromise__["fromPromise"])(r) : r;
if (!(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["g" /* ɵisObservable */])(obs))) {
throw new Error("Expected validator to return Promise or Observable.");
}
return obs;
}
/**
* @param {?} control
* @param {?} validators
* @return {?}
*/
function _executeValidators(control, validators) {
return validators.map(function (v) { return v(control); });
}
/**
* @param {?} control
* @param {?} validators
* @return {?}
*/
function _executeAsyncValidators(control, validators) {
return validators.map(function (v) { return v(control); });
}
/**
* @param {?} arrayOfErrors
* @return {?}
*/
function _mergeErrors(arrayOfErrors) {
var /** @type {?} */ res = arrayOfErrors.reduce(function (res, errors) {
return errors != null ? __assign({}, /** @type {?} */ ((res)), errors) : ((res));
}, {});
return Object.keys(res).length === 0 ? null : res;
}
/**
* @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
*/
/**
* Used to provide a {\@link ControlValueAccessor} for form controls.
*
* See {\@link DefaultValueAccessor} for how to implement one.
* \@stable
*/
var NG_VALUE_ACCESSOR = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('NgValueAccessor');
/**
* @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
*/
var CHECKBOX_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return CheckboxControlValueAccessor; }),
multi: true,
};
/**
* The accessor for writing a value and listening to changes on a checkbox input element.
*
* ### Example
* ```
* <input type="checkbox" name="rememberLogin" ngModel>
* ```
*
* \@stable
*/
var CheckboxControlValueAccessor = (function () {
/**
* @param {?} _renderer
* @param {?} _elementRef
*/
function CheckboxControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = function (_) { };
this.onTouched = function () { };
}
/**
* @param {?} value
* @return {?}
*/
CheckboxControlValueAccessor.prototype.writeValue = function (value) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value);
};
/**
* @param {?} fn
* @return {?}
*/
CheckboxControlValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
/**
* @param {?} fn
* @return {?}
*/
CheckboxControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* @param {?} isDisabled
* @return {?}
*/
CheckboxControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
return CheckboxControlValueAccessor;
}());
CheckboxControlValueAccessor.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]',
host: { '(change)': 'onChange($event.target.checked)', '(blur)': 'onTouched()' },
providers: [CHECKBOX_VALUE_ACCESSOR]
},] },
];
/**
* @nocollapse
*/
CheckboxControlValueAccessor.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
]; };
/**
* @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
*/
var DEFAULT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return DefaultValueAccessor; }),
multi: true
};
/**
* We must check whether the agent is Android because composition events
* behave differently between iOS and Android.
* @return {?}
*/
function _isAndroid() {
var /** @type {?} */ userAgent = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__angular_platform_browser__["c" /* ɵgetDOM */])() ? __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__angular_platform_browser__["c" /* ɵgetDOM */])().getUserAgent() : '';
return /android (\d+)/.test(userAgent.toLowerCase());
}
/**
* Turn this mode on if you want form directives to buffer IME input until compositionend
* \@experimental
*/
var COMPOSITION_BUFFER_MODE = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('CompositionEventMode');
/**
* The default accessor for writing a value and listening to changes that is used by the
* {\@link NgModel}, {\@link FormControlDirective}, and {\@link FormControlName} directives.
*
* ### Example
* ```
* <input type="text" name="searchQuery" ngModel>
* ```
*
* \@stable
*/
var DefaultValueAccessor = (function () {
/**
* @param {?} _renderer
* @param {?} _elementRef
* @param {?} _compositionMode
*/
function DefaultValueAccessor(_renderer, _elementRef, _compositionMode) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this._compositionMode = _compositionMode;
this.onChange = function (_) { };
this.onTouched = function () { };
this._composing = false;
if (this._compositionMode == null) {
this._compositionMode = !_isAndroid();
}
}
/**
* @param {?} value
* @return {?}
*/
DefaultValueAccessor.prototype.writeValue = function (value) {
var /** @type {?} */ normalizedValue = value == null ? '' : value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
};
/**
* @param {?} fn
* @return {?}
*/
DefaultValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
/**
* @param {?} fn
* @return {?}
*/
DefaultValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* @param {?} isDisabled
* @return {?}
*/
DefaultValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/**
* @param {?} value
* @return {?}
*/
DefaultValueAccessor.prototype._handleInput = function (value) {
if (!this._compositionMode || (this._compositionMode && !this._composing)) {
this.onChange(value);
}
};
/**
* @return {?}
*/
DefaultValueAccessor.prototype._compositionStart = function () { this._composing = true; };
/**
* @param {?} value
* @return {?}
*/
DefaultValueAccessor.prototype._compositionEnd = function (value) {
this._composing = false;
this._compositionMode && this.onChange(value);
};
return DefaultValueAccessor;
}());
DefaultValueAccessor.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
// TODO: vsavkin replace the above selector with the one below it once
// https://github.com/angular/angular/issues/3011 is implemented
// selector: '[ngModel],[formControl],[formControlName]',
host: {
'(input)': '_handleInput($event.target.value)',
'(blur)': 'onTouched()',
'(compositionstart)': '_compositionStart()',
'(compositionend)': '_compositionEnd($event.target.value)'
},
providers: [DEFAULT_VALUE_ACCESSOR]
},] },
];
/**
* @nocollapse
*/
DefaultValueAccessor.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [COMPOSITION_BUFFER_MODE,] },] },
]; };
/**
* @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
*/
/**
* @param {?} validator
* @return {?}
*/
function normalizeValidator(validator) {
if (((validator)).validate) {
return function (c) { return ((validator)).validate(c); };
}
else {
return (validator);
}
}
/**
* @param {?} validator
* @return {?}
*/
function normalizeAsyncValidator(validator) {
if (((validator)).validate) {
return function (c) { return ((validator)).validate(c); };
}
else {
return (validator);
}
}
/**
* @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
*/
var NUMBER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return NumberValueAccessor; }),
multi: true
};
/**
* The accessor for writing a number value and listening to changes that is used by the
* {\@link NgModel}, {\@link FormControlDirective}, and {\@link FormControlName} directives.
*
* ### Example
* ```
* <input type="number" [(ngModel)]="age">
* ```
*/
var NumberValueAccessor = (function () {
/**
* @param {?} _renderer
* @param {?} _elementRef
*/
function NumberValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = function (_) { };
this.onTouched = function () { };
}
/**
* @param {?} value
* @return {?}
*/
NumberValueAccessor.prototype.writeValue = function (value) {
// The value needs to be normalized for IE9, otherwise it is set to 'null' when null
var /** @type {?} */ normalizedValue = value == null ? '' : value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
};
/**
* @param {?} fn
* @return {?}
*/
NumberValueAccessor.prototype.registerOnChange = function (fn) {
this.onChange = function (value) { fn(value == '' ? null : parseFloat(value)); };
};
/**
* @param {?} fn
* @return {?}
*/
NumberValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* @param {?} isDisabled
* @return {?}
*/
NumberValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
return NumberValueAccessor;
}());
NumberValueAccessor.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]',
host: {
'(change)': 'onChange($event.target.value)',
'(input)': 'onChange($event.target.value)',
'(blur)': 'onTouched()'
},
providers: [NUMBER_VALUE_ACCESSOR]
},] },
];
/**
* @nocollapse
*/
NumberValueAccessor.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
]; };
/**
* @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
*/
/**
* @return {?}
*/
function unimplemented() {
throw new Error('unimplemented');
}
/**
* A base class that all control directive extend.
* It binds a {\@link FormControl} object to a DOM element.
*
* Used internally by Angular forms.
*
* \@stable
* @abstract
*/
var NgControl = (function (_super) {
__extends(NgControl, _super);
function NgControl() {
var _this = _super.apply(this, arguments) || this;
/**
* \@internal
*/
_this._parent = null;
_this.name = null;
_this.valueAccessor = null;
/**
* \@internal
*/
_this._rawValidators = [];
/**
* \@internal
*/
_this._rawAsyncValidators = [];
return _this;
}
Object.defineProperty(NgControl.prototype, "validator", {
/**
* @return {?}
*/
get: function () { return (unimplemented()); },
enumerable: true,
configurable: true
});
Object.defineProperty(NgControl.prototype, "asyncValidator", {
/**
* @return {?}
*/
get: function () { return (unimplemented()); },
enumerable: true,
configurable: true
});
/**
* @abstract
* @param {?} newValue
* @return {?}
*/
NgControl.prototype.viewToModelUpdate = function (newValue) { };
return NgControl;
}(AbstractControlDirective));
/**
* @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
*/
var RADIO_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return RadioControlValueAccessor; }),
multi: true
};
/**
* Internal class used by Angular to uncheck radio buttons with the matching name.
*/
var RadioControlRegistry = (function () {
function RadioControlRegistry() {
this._accessors = [];
}
/**
* @param {?} control
* @param {?} accessor
* @return {?}
*/
RadioControlRegistry.prototype.add = function (control, accessor) {
this._accessors.push([control, accessor]);
};
/**
* @param {?} accessor
* @return {?}
*/
RadioControlRegistry.prototype.remove = function (accessor) {
for (var /** @type {?} */ i = this._accessors.length - 1; i >= 0; --i) {
if (this._accessors[i][1] === accessor) {
this._accessors.splice(i, 1);
return;
}
}
};
/**
* @param {?} accessor
* @return {?}
*/
RadioControlRegistry.prototype.select = function (accessor) {
var _this = this;
this._accessors.forEach(function (c) {
if (_this._isSameGroup(c, accessor) && c[1] !== accessor) {
c[1].fireUncheck(accessor.value);
}
});
};
/**
* @param {?} controlPair
* @param {?} accessor
* @return {?}
*/
RadioControlRegistry.prototype._isSameGroup = function (controlPair, accessor) {
if (!controlPair[0].control)
return false;
return controlPair[0]._parent === accessor._control._parent &&
controlPair[1].name === accessor.name;
};
return RadioControlRegistry;
}());
RadioControlRegistry.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
RadioControlRegistry.ctorParameters = function () { return []; };
/**
* \@whatItDoes Writes radio control values and listens to radio control changes.
*
* Used by {\@link NgModel}, {\@link FormControlDirective}, and {\@link FormControlName}
* to keep the view synced with the {\@link FormControl} model.
*
* \@howToUse
*
* If you have imported the {\@link FormsModule} or the {\@link ReactiveFormsModule}, this
* value accessor will be active on any radio control that has a form directive. You do
* **not** need to add a special selector to activate it.
*
* ### How to use radio buttons with form directives
*
* To use radio buttons in a template-driven form, you'll want to ensure that radio buttons
* in the same group have the same `name` attribute. Radio buttons with different `name`
* attributes do not affect each other.
*
* {\@example forms/ts/radioButtons/radio_button_example.ts region='TemplateDriven'}
*
* When using radio buttons in a reactive form, radio buttons in the same group should have the
* same `formControlName`. You can also add a `name` attribute, but it's optional.
*
* {\@example forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts region='Reactive'}
*
* * **npm package**: `\@angular/forms`
*
* \@stable
*/
var RadioControlValueAccessor = (function () {
/**
* @param {?} _renderer
* @param {?} _elementRef
* @param {?} _registry
* @param {?} _injector
*/
function RadioControlValueAccessor(_renderer, _elementRef, _registry, _injector) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this._registry = _registry;
this._injector = _injector;
this.onChange = function () { };
this.onTouched = function () { };
}
/**
* @return {?}
*/
RadioControlValueAccessor.prototype.ngOnInit = function () {
this._control = this._injector.get(NgControl);
this._checkName();
this._registry.add(this._control, this);
};
/**
* @return {?}
*/
RadioControlValueAccessor.prototype.ngOnDestroy = function () { this._registry.remove(this); };
/**
* @param {?} value
* @return {?}
*/
RadioControlValueAccessor.prototype.writeValue = function (value) {
this._state = value === this.value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', this._state);
};
/**
* @param {?} fn
* @return {?}
*/
RadioControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this._fn = fn;
this.onChange = function () {
fn(_this.value);
_this._registry.select(_this);
};
};
/**
* @param {?} value
* @return {?}
*/
RadioControlValueAccessor.prototype.fireUncheck = function (value) { this.writeValue(value); };
/**
* @param {?} fn
* @return {?}
*/
RadioControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* @param {?} isDisabled
* @return {?}
*/
RadioControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/**
* @return {?}
*/
RadioControlValueAccessor.prototype._checkName = function () {
if (this.name && this.formControlName && this.name !== this.formControlName) {
this._throwNameError();
}
if (!this.name && this.formControlName)
this.name = this.formControlName;
};
/**
* @return {?}
*/
RadioControlValueAccessor.prototype._throwNameError = function () {
throw new Error("\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: <input type=\"radio\" formControlName=\"food\" name=\"food\">\n ");
};
return RadioControlValueAccessor;
}());
RadioControlValueAccessor.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]',
host: { '(change)': 'onChange()', '(blur)': 'onTouched()' },
providers: [RADIO_VALUE_ACCESSOR]
},] },
];
/**
* @nocollapse
*/
RadioControlValueAccessor.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
{ type: RadioControlRegistry, },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Injector */], },
]; };
RadioControlValueAccessor.propDecorators = {
'name': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'formControlName': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'value': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* @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
*/
var RANGE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return RangeValueAccessor; }),
multi: true
};
/**
* The accessor for writing a range value and listening to changes that is used by the
* {\@link NgModel}, {\@link FormControlDirective}, and {\@link FormControlName} directives.
*
* ### Example
* ```
* <input type="range" [(ngModel)]="age" >
* ```
*/
var RangeValueAccessor = (function () {
/**
* @param {?} _renderer
* @param {?} _elementRef
*/
function RangeValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = function (_) { };
this.onTouched = function () { };
}
/**
* @param {?} value
* @return {?}
*/
RangeValueAccessor.prototype.writeValue = function (value) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', parseFloat(value));
};
/**
* @param {?} fn
* @return {?}
*/
RangeValueAccessor.prototype.registerOnChange = function (fn) {
this.onChange = function (value) { fn(value == '' ? null : parseFloat(value)); };
};
/**
* @param {?} fn
* @return {?}
*/
RangeValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* @param {?} isDisabled
* @return {?}
*/
RangeValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
return RangeValueAccessor;
}());
RangeValueAccessor.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]',
host: {
'(change)': 'onChange($event.target.value)',
'(input)': 'onChange($event.target.value)',
'(blur)': 'onTouched()'
},
providers: [RANGE_VALUE_ACCESSOR]
},] },
];
/**
* @nocollapse
*/
RangeValueAccessor.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
]; };
/**
* @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
*/
var SELECT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return SelectControlValueAccessor; }),
multi: true
};
/**
* @param {?} id
* @param {?} value
* @return {?}
*/
function _buildValueString(id, value) {
if (id == null)
return "" + value;
if (value && typeof value === 'object')
value = 'Object';
return (id + ": " + value).slice(0, 50);
}
/**
* @param {?} valueString
* @return {?}
*/
function _extractId(valueString) {
return valueString.split(':')[0];
}
/**
* \@whatItDoes Writes values and listens to changes on a select element.
*
* Used by {\@link NgModel}, {\@link FormControlDirective}, and {\@link FormControlName}
* to keep the view synced with the {\@link FormControl} model.
*
* \@howToUse
*
* If you have imported the {\@link FormsModule} or the {\@link ReactiveFormsModule}, this
* value accessor will be active on any select control that has a form directive. You do
* **not** need to add a special selector to activate it.
*
* ### How to use select controls with form directives
*
* To use a select in a template-driven form, simply add an `ngModel` and a `name`
* attribute to the main `<select>` tag.
*
* If your option values are simple strings, you can bind to the normal `value` property
* on the option. If your option values happen to be objects (and you'd like to save the
* selection in your form as an object), use `ngValue` instead:
*
* {\@example forms/ts/selectControl/select_control_example.ts region='Component'}
*
* In reactive forms, you'll also want to add your form directive (`formControlName` or
* `formControl`) on the main `<select>` tag. Like in the former example, you have the
* choice of binding to the `value` or `ngValue` property on the select's options.
*
* {\@example forms/ts/reactiveSelectControl/reactive_select_control_example.ts region='Component'}
*
* ### Caveat: Option selection
*
* Angular uses object identity to select option. It's possible for the identities of items
* to change while the data does not. This can happen, for example, if the items are produced
* from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the
* second response will produce objects with different identities.
*
* To customize the default option comparison algorithm, `<select>` supports `compareWith` input.
* `compareWith` takes a **function** which has two arguments: `option1` and `option2`.
* If `compareWith` is given, Angular selects option by the return value of the function.
*
* #### Syntax
*
* ```
* <select [compareWith]="compareFn" [(ngModel)]="selectedCountries">
* <option *ngFor="let country of countries" [ngValue]="country">
* {{country.name}}
* </option>
* </select>
*
* compareFn(c1: Country, c2: Country): boolean {
* return c1 && c2 ? c1.id === c2.id : c1 === c2;
* }
* ```
*
* Note: We listen to the 'change' event because 'input' events aren't fired
* for selects in Firefox and IE:
* https://bugzilla.mozilla.org/show_bug.cgi?id=1024350
* https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4660045/
*
* * **npm package**: `\@angular/forms`
*
* \@stable
*/
var SelectControlValueAccessor = (function () {
/**
* @param {?} _renderer
* @param {?} _elementRef
*/
function SelectControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/**
* \@internal
*/
this._optionMap = new Map();
/**
* \@internal
*/
this._idCounter = 0;
this.onChange = function (_) { };
this.onTouched = function () { };
this._compareWith = __WEBPACK_IMPORTED_MODULE_0__angular_core__["o" /* ɵlooseIdentical */];
}
Object.defineProperty(SelectControlValueAccessor.prototype, "compareWith", {
/**
* @param {?} fn
* @return {?}
*/
set: function (fn) {
if (typeof fn !== 'function') {
throw new Error("compareWith must be a function, but received " + JSON.stringify(fn));
}
this._compareWith = fn;
},
enumerable: true,
configurable: true
});
/**
* @param {?} value
* @return {?}
*/
SelectControlValueAccessor.prototype.writeValue = function (value) {
this.value = value;
var /** @type {?} */ id = this._getOptionId(value);
if (id == null) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'selectedIndex', -1);
}
var /** @type {?} */ valueString = _buildValueString(id, value);
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', valueString);
};
/**
* @param {?} fn
* @return {?}
*/
SelectControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this.onChange = function (valueString) {
_this.value = valueString;
fn(_this._getOptionValue(valueString));
};
};
/**
* @param {?} fn
* @return {?}
*/
SelectControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* @param {?} isDisabled
* @return {?}
*/
SelectControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/**
* \@internal
* @return {?}
*/
SelectControlValueAccessor.prototype._registerOption = function () { return (this._idCounter++).toString(); };
/**
* \@internal
* @param {?} value
* @return {?}
*/
SelectControlValueAccessor.prototype._getOptionId = function (value) {
for (var _i = 0, _a = Array.from(this._optionMap.keys()); _i < _a.length; _i++) {
var id = _a[_i];
if (this._compareWith(this._optionMap.get(id), value))
return id;
}
return null;
};
/**
* \@internal
* @param {?} valueString
* @return {?}
*/
SelectControlValueAccessor.prototype._getOptionValue = function (valueString) {
var /** @type {?} */ id = _extractId(valueString);
return this._optionMap.has(id) ? this._optionMap.get(id) : valueString;
};
return SelectControlValueAccessor;
}());
SelectControlValueAccessor.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]',
host: { '(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()' },
providers: [SELECT_VALUE_ACCESSOR]
},] },
];
/**
* @nocollapse
*/
SelectControlValueAccessor.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
]; };
SelectControlValueAccessor.propDecorators = {
'compareWith': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* \@whatItDoes Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* \@howToUse
*
* See docs for {\@link SelectControlValueAccessor} for usage examples.
*
* \@stable
*/
var NgSelectOption = (function () {
/**
* @param {?} _element
* @param {?} _renderer
* @param {?} _select
*/
function NgSelectOption(_element, _renderer, _select) {
this._element = _element;
this._renderer = _renderer;
this._select = _select;
if (this._select)
this.id = this._select._registerOption();
}
Object.defineProperty(NgSelectOption.prototype, "ngValue", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
if (this._select == null)
return;
this._select._optionMap.set(this.id, value);
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgSelectOption.prototype, "value", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
this._setElementValue(value);
if (this._select)
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
/**
* \@internal
* @param {?} value
* @return {?}
*/
NgSelectOption.prototype._setElementValue = function (value) {
this._renderer.setElementProperty(this._element.nativeElement, 'value', value);
};
/**
* @return {?}
*/
NgSelectOption.prototype.ngOnDestroy = function () {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
};
return NgSelectOption;
}());
NgSelectOption.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: 'option' },] },
];
/**
* @nocollapse
*/
NgSelectOption.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: SelectControlValueAccessor, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] },] },
]; };
NgSelectOption.propDecorators = {
'ngValue': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['ngValue',] },],
'value': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['value',] },],
};
/**
* @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
*/
var SELECT_MULTIPLE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return SelectMultipleControlValueAccessor; }),
multi: true
};
/**
* @param {?} id
* @param {?} value
* @return {?}
*/
function _buildValueString$1(id, value) {
if (id == null)
return "" + value;
if (typeof value === 'string')
value = "'" + value + "'";
if (value && typeof value === 'object')
value = 'Object';
return (id + ": " + value).slice(0, 50);
}
/**
* @param {?} valueString
* @return {?}
*/
function _extractId$1(valueString) {
return valueString.split(':')[0];
}
/**
* The accessor for writing a value and listening to changes on a select element.
*
* ### Caveat: Options selection
*
* Angular uses object identity to select options. It's possible for the identities of items
* to change while the data does not. This can happen, for example, if the items are produced
* from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the
* second response will produce objects with different identities.
*
* To customize the default option comparison algorithm, `<select multiple>` supports `compareWith`
* input. `compareWith` takes a **function** which has two arguments: `option1` and `option2`.
* If `compareWith` is given, Angular selects options by the return value of the function.
*
* #### Syntax
*
* ```
* <select multiple [compareWith]="compareFn" [(ngModel)]="selectedCountries">
* <option *ngFor="let country of countries" [ngValue]="country">
* {{country.name}}
* </option>
* </select>
*
* compareFn(c1: Country, c2: Country): boolean {
* return c1 && c2 ? c1.id === c2.id : c1 === c2;
* }
* ```
*
* \@stable
*/
var SelectMultipleControlValueAccessor = (function () {
/**
* @param {?} _renderer
* @param {?} _elementRef
*/
function SelectMultipleControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/**
* \@internal
*/
this._optionMap = new Map();
/**
* \@internal
*/
this._idCounter = 0;
this.onChange = function (_) { };
this.onTouched = function () { };
this._compareWith = __WEBPACK_IMPORTED_MODULE_0__angular_core__["o" /* ɵlooseIdentical */];
}
Object.defineProperty(SelectMultipleControlValueAccessor.prototype, "compareWith", {
/**
* @param {?} fn
* @return {?}
*/
set: function (fn) {
if (typeof fn !== 'function') {
throw new Error("compareWith must be a function, but received " + JSON.stringify(fn));
}
this._compareWith = fn;
},
enumerable: true,
configurable: true
});
/**
* @param {?} value
* @return {?}
*/
SelectMultipleControlValueAccessor.prototype.writeValue = function (value) {
var _this = this;
this.value = value;
var /** @type {?} */ optionSelectedStateSetter;
if (Array.isArray(value)) {
// convert values to ids
var /** @type {?} */ ids_1 = value.map(function (v) { return _this._getOptionId(v); });
optionSelectedStateSetter = function (opt, o) { opt._setSelected(ids_1.indexOf(o.toString()) > -1); };
}
else {
optionSelectedStateSetter = function (opt, o) { opt._setSelected(false); };
}
this._optionMap.forEach(optionSelectedStateSetter);
};
/**
* @param {?} fn
* @return {?}
*/
SelectMultipleControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this.onChange = function (_) {
var /** @type {?} */ selected = [];
if (_.hasOwnProperty('selectedOptions')) {
var /** @type {?} */ options = _.selectedOptions;
for (var /** @type {?} */ i = 0; i < options.length; i++) {
var /** @type {?} */ opt = options.item(i);
var /** @type {?} */ val = _this._getOptionValue(opt.value);
selected.push(val);
}
}
else {
var /** @type {?} */ options = (_.options);
for (var /** @type {?} */ i = 0; i < options.length; i++) {
var /** @type {?} */ opt = options.item(i);
if (opt.selected) {
var /** @type {?} */ val = _this._getOptionValue(opt.value);
selected.push(val);
}
}
}
_this.value = selected;
fn(selected);
};
};
/**
* @param {?} fn
* @return {?}
*/
SelectMultipleControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* @param {?} isDisabled
* @return {?}
*/
SelectMultipleControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/**
* \@internal
* @param {?} value
* @return {?}
*/
SelectMultipleControlValueAccessor.prototype._registerOption = function (value) {
var /** @type {?} */ id = (this._idCounter++).toString();
this._optionMap.set(id, value);
return id;
};
/**
* \@internal
* @param {?} value
* @return {?}
*/
SelectMultipleControlValueAccessor.prototype._getOptionId = function (value) {
for (var _i = 0, _a = Array.from(this._optionMap.keys()); _i < _a.length; _i++) {
var id = _a[_i];
if (this._compareWith(/** @type {?} */ ((this._optionMap.get(id)))._value, value))
return id;
}
return null;
};
/**
* \@internal
* @param {?} valueString
* @return {?}
*/
SelectMultipleControlValueAccessor.prototype._getOptionValue = function (valueString) {
var /** @type {?} */ id = _extractId$1(valueString);
return this._optionMap.has(id) ? ((this._optionMap.get(id)))._value : valueString;
};
return SelectMultipleControlValueAccessor;
}());
SelectMultipleControlValueAccessor.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]',
host: { '(change)': 'onChange($event.target)', '(blur)': 'onTouched()' },
providers: [SELECT_MULTIPLE_VALUE_ACCESSOR]
},] },
];
/**
* @nocollapse
*/
SelectMultipleControlValueAccessor.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
]; };
SelectMultipleControlValueAccessor.propDecorators = {
'compareWith': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* ### Example
*
* ```
* <select multiple name="city" ngModel>
* <option *ngFor="let c of cities" [value]="c"></option>
* </select>
* ```
*/
var NgSelectMultipleOption = (function () {
/**
* @param {?} _element
* @param {?} _renderer
* @param {?} _select
*/
function NgSelectMultipleOption(_element, _renderer, _select) {
this._element = _element;
this._renderer = _renderer;
this._select = _select;
if (this._select) {
this.id = this._select._registerOption(this);
}
}
Object.defineProperty(NgSelectMultipleOption.prototype, "ngValue", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
if (this._select == null)
return;
this._value = value;
this._setElementValue(_buildValueString$1(this.id, value));
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgSelectMultipleOption.prototype, "value", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
if (this._select) {
this._value = value;
this._setElementValue(_buildValueString$1(this.id, value));
this._select.writeValue(this._select.value);
}
else {
this._setElementValue(value);
}
},
enumerable: true,
configurable: true
});
/**
* \@internal
* @param {?} value
* @return {?}
*/
NgSelectMultipleOption.prototype._setElementValue = function (value) {
this._renderer.setElementProperty(this._element.nativeElement, 'value', value);
};
/**
* \@internal
* @param {?} selected
* @return {?}
*/
NgSelectMultipleOption.prototype._setSelected = function (selected) {
this._renderer.setElementProperty(this._element.nativeElement, 'selected', selected);
};
/**
* @return {?}
*/
NgSelectMultipleOption.prototype.ngOnDestroy = function () {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
};
return NgSelectMultipleOption;
}());
NgSelectMultipleOption.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: 'option' },] },
];
/**
* @nocollapse
*/
NgSelectMultipleOption.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
{ type: SelectMultipleControlValueAccessor, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] },] },
]; };
NgSelectMultipleOption.propDecorators = {
'ngValue': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['ngValue',] },],
'value': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['value',] },],
};
/**
* @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
*/
/**
* @param {?} name
* @param {?} parent
* @return {?}
*/
function controlPath(name, parent) {
return ((parent.path)).concat([name]);
}
/**
* @param {?} control
* @param {?} dir
* @return {?}
*/
function setUpControl(control, dir) {
if (!control)
_throwError(dir, 'Cannot find control with');
if (!dir.valueAccessor)
_throwError(dir, 'No value accessor for form control with');
control.validator = Validators.compose([/** @type {?} */ ((control.validator)), dir.validator]);
control.asyncValidator = Validators.composeAsync([/** @type {?} */ ((control.asyncValidator)), dir.asyncValidator]); /** @type {?} */
((dir.valueAccessor)).writeValue(control.value); /** @type {?} */
((
// view -> model
dir.valueAccessor)).registerOnChange(function (newValue) {
dir.viewToModelUpdate(newValue);
control.markAsDirty();
control.setValue(newValue, { emitModelToViewChange: false });
}); /** @type {?} */
((
// touched
dir.valueAccessor)).registerOnTouched(function () { return control.markAsTouched(); });
control.registerOnChange(function (newValue, emitModelEvent) {
((
// control -> view
dir.valueAccessor)).writeValue(newValue);
// control -> ngModel
if (emitModelEvent)
dir.viewToModelUpdate(newValue);
});
if (((dir.valueAccessor)).setDisabledState) {
control.registerOnDisabledChange(function (isDisabled) { /** @type {?} */ ((((dir.valueAccessor)).setDisabledState))(isDisabled); });
}
// re-run validation when validator binding changes, e.g. minlength=3 -> minlength=4
dir._rawValidators.forEach(function (validator) {
if (((validator)).registerOnValidatorChange)
((((validator)).registerOnValidatorChange))(function () { return control.updateValueAndValidity(); });
});
dir._rawAsyncValidators.forEach(function (validator) {
if (((validator)).registerOnValidatorChange)
((((validator)).registerOnValidatorChange))(function () { return control.updateValueAndValidity(); });
});
}
/**
* @param {?} control
* @param {?} dir
* @return {?}
*/
function cleanUpControl(control, dir) {
((dir.valueAccessor)).registerOnChange(function () { return _noControlError(dir); }); /** @type {?} */
((dir.valueAccessor)).registerOnTouched(function () { return _noControlError(dir); });
dir._rawValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange) {
validator.registerOnValidatorChange(null);
}
});
dir._rawAsyncValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange) {
validator.registerOnValidatorChange(null);
}
});
if (control)
control._clearChangeFns();
}
/**
* @param {?} control
* @param {?} dir
* @return {?}
*/
function setUpFormContainer(control, dir) {
if (control == null)
_throwError(dir, 'Cannot find control with');
control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
}
/**
* @param {?} dir
* @return {?}
*/
function _noControlError(dir) {
return _throwError(dir, 'There is no FormControl instance attached to form control element with');
}
/**
* @param {?} dir
* @param {?} message
* @return {?}
*/
function _throwError(dir, message) {
var /** @type {?} */ messageEnd;
if (((dir.path)).length > 1) {
messageEnd = "path: '" + ((dir.path)).join(' -> ') + "'";
}
else if (((dir.path))[0]) {
messageEnd = "name: '" + dir.path + "'";
}
else {
messageEnd = 'unspecified name attribute';
}
throw new Error(message + " " + messageEnd);
}
/**
* @param {?} validators
* @return {?}
*/
function composeValidators(validators) {
return validators != null ? Validators.compose(validators.map(normalizeValidator)) : null;
}
/**
* @param {?} validators
* @return {?}
*/
function composeAsyncValidators(validators) {
return validators != null ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
}
/**
* @param {?} changes
* @param {?} viewModel
* @return {?}
*/
function isPropertyUpdated(changes, viewModel) {
if (!changes.hasOwnProperty('model'))
return false;
var /** @type {?} */ change = changes['model'];
if (change.isFirstChange())
return true;
return !__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["o" /* ɵlooseIdentical */])(viewModel, change.currentValue);
}
var BUILTIN_ACCESSORS = [
CheckboxControlValueAccessor,
RangeValueAccessor,
NumberValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
];
/**
* @param {?} valueAccessor
* @return {?}
*/
function isBuiltInAccessor(valueAccessor) {
return BUILTIN_ACCESSORS.some(function (a) { return valueAccessor.constructor === a; });
}
/**
* @param {?} dir
* @param {?} valueAccessors
* @return {?}
*/
function selectValueAccessor(dir, valueAccessors) {
if (!valueAccessors)
return null;
var /** @type {?} */ defaultAccessor = undefined;
var /** @type {?} */ builtinAccessor = undefined;
var /** @type {?} */ customAccessor = undefined;
valueAccessors.forEach(function (v) {
if (v.constructor === DefaultValueAccessor) {
defaultAccessor = v;
}
else if (isBuiltInAccessor(v)) {
if (builtinAccessor)
_throwError(dir, 'More than one built-in value accessor matches form control with');
builtinAccessor = v;
}
else {
if (customAccessor)
_throwError(dir, 'More than one custom value accessor matches form control with');
customAccessor = v;
}
});
if (customAccessor)
return customAccessor;
if (builtinAccessor)
return builtinAccessor;
if (defaultAccessor)
return defaultAccessor;
_throwError(dir, 'No valid value accessor for form control with');
return null;
}
/**
* @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
*/
/**
* This is a base class for code shared between {\@link NgModelGroup} and {\@link FormGroupName}.
*
* \@stable
*/
var AbstractFormGroupDirective = (function (_super) {
__extends(AbstractFormGroupDirective, _super);
function AbstractFormGroupDirective() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @return {?}
*/
AbstractFormGroupDirective.prototype.ngOnInit = function () {
this._checkParentType(); /** @type {?} */
((this.formDirective)).addFormGroup(this);
};
/**
* @return {?}
*/
AbstractFormGroupDirective.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeFormGroup(this);
}
};
Object.defineProperty(AbstractFormGroupDirective.prototype, "control", {
/**
* Get the {\@link FormGroup} backing this binding.
* @return {?}
*/
get: function () { return ((this.formDirective)).getFormGroup(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "path", {
/**
* Get the path to this control group.
* @return {?}
*/
get: function () { return controlPath(this.name, this._parent); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "formDirective", {
/**
* Get the {\@link Form} to which this group belongs.
* @return {?}
*/
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "validator", {
/**
* @return {?}
*/
get: function () { return composeValidators(this._validators); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "asyncValidator", {
/**
* @return {?}
*/
get: function () {
return composeAsyncValidators(this._asyncValidators);
},
enumerable: true,
configurable: true
});
/**
* \@internal
* @return {?}
*/
AbstractFormGroupDirective.prototype._checkParentType = function () { };
return AbstractFormGroupDirective;
}(ControlContainer));
/**
* @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
*/
var AbstractControlStatus = (function () {
/**
* @param {?} cd
*/
function AbstractControlStatus(cd) {
this._cd = cd;
}
Object.defineProperty(AbstractControlStatus.prototype, "ngClassUntouched", {
/**
* @return {?}
*/
get: function () { return this._cd.control ? this._cd.control.untouched : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassTouched", {
/**
* @return {?}
*/
get: function () { return this._cd.control ? this._cd.control.touched : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassPristine", {
/**
* @return {?}
*/
get: function () { return this._cd.control ? this._cd.control.pristine : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassDirty", {
/**
* @return {?}
*/
get: function () { return this._cd.control ? this._cd.control.dirty : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassValid", {
/**
* @return {?}
*/
get: function () { return this._cd.control ? this._cd.control.valid : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassInvalid", {
/**
* @return {?}
*/
get: function () { return this._cd.control ? this._cd.control.invalid : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassPending", {
/**
* @return {?}
*/
get: function () { return this._cd.control ? this._cd.control.pending : false; },
enumerable: true,
configurable: true
});
return AbstractControlStatus;
}());
var ngControlStatusHost = {
'[class.ng-untouched]': 'ngClassUntouched',
'[class.ng-touched]': 'ngClassTouched',
'[class.ng-pristine]': 'ngClassPristine',
'[class.ng-dirty]': 'ngClassDirty',
'[class.ng-valid]': 'ngClassValid',
'[class.ng-invalid]': 'ngClassInvalid',
'[class.ng-pending]': 'ngClassPending',
};
/**
* Directive automatically applied to Angular form controls that sets CSS classes
* based on control status (valid/invalid/dirty/etc).
*
* \@stable
*/
var NgControlStatus = (function (_super) {
__extends(NgControlStatus, _super);
/**
* @param {?} cd
*/
function NgControlStatus(cd) {
return _super.call(this, cd) || this;
}
return NgControlStatus;
}(AbstractControlStatus));
NgControlStatus.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[formControlName],[ngModel],[formControl]', host: ngControlStatusHost },] },
];
/**
* @nocollapse
*/
NgControlStatus.ctorParameters = function () { return [
{ type: NgControl, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] },] },
]; };
/**
* Directive automatically applied to Angular form groups that sets CSS classes
* based on control status (valid/invalid/dirty/etc).
*
* \@stable
*/
var NgControlStatusGroup = (function (_super) {
__extends(NgControlStatusGroup, _super);
/**
* @param {?} cd
*/
function NgControlStatusGroup(cd) {
return _super.call(this, cd) || this;
}
return NgControlStatusGroup;
}(AbstractControlStatus));
NgControlStatusGroup.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: '[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]',
host: ngControlStatusHost
},] },
];
/**
* @nocollapse
*/
NgControlStatusGroup.ctorParameters = function () { return [
{ type: ControlContainer, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] },] },
]; };
/**
* @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
*/
/**
* Indicates that a FormControl is valid, i.e. that no errors exist in the input value.
*/
var VALID = 'VALID';
/**
* Indicates that a FormControl is invalid, i.e. that an error exists in the input value.
*/
var INVALID = 'INVALID';
/**
* Indicates that a FormControl is pending, i.e. that async validation is occurring and
* errors are not yet available for the input value.
*/
var PENDING = 'PENDING';
/**
* Indicates that a FormControl is disabled, i.e. that the control is exempt from ancestor
* calculations of validity or value.
*/
var DISABLED = 'DISABLED';
/**
* @param {?} control
* @param {?} path
* @param {?} delimiter
* @return {?}
*/
function _find(control, path, delimiter) {
if (path == null)
return null;
if (!(path instanceof Array)) {
path = ((path)).split(delimiter);
}
if (path instanceof Array && (path.length === 0))
return null;
return ((path)).reduce(function (v, name) {
if (v instanceof FormGroup) {
return v.controls[name] || null;
}
if (v instanceof FormArray) {
return v.at(/** @type {?} */ (name)) || null;
}
return null;
}, control);
}
/**
* @param {?=} validator
* @return {?}
*/
function coerceToValidator(validator) {
return Array.isArray(validator) ? composeValidators(validator) : validator || null;
}
/**
* @param {?=} asyncValidator
* @return {?}
*/
function coerceToAsyncValidator(asyncValidator) {
return Array.isArray(asyncValidator) ? composeAsyncValidators(asyncValidator) :
asyncValidator || null;
}
/**
* \@whatItDoes This is the base class for {\@link FormControl}, {\@link FormGroup}, and
* {\@link FormArray}.
*
* It provides some of the shared behavior that all controls and groups of controls have, like
* running validators, calculating status, and resetting state. It also defines the properties
* that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be
* instantiated directly.
*
* \@stable
* @abstract
*/
var AbstractControl = (function () {
/**
* @param {?} validator
* @param {?} asyncValidator
*/
function AbstractControl(validator, asyncValidator) {
this.validator = validator;
this.asyncValidator = asyncValidator;
/**
* \@internal
*/
this._onCollectionChange = function () { };
this._pristine = true;
this._touched = false;
/**
* \@internal
*/
this._onDisabledChange = [];
}
Object.defineProperty(AbstractControl.prototype, "value", {
/**
* The value of the control.
* @return {?}
*/
get: function () { return this._value; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "parent", {
/**
* The parent control.
* @return {?}
*/
get: function () { return this._parent; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "status", {
/**
* The validation status of the control. There are four possible
* validation statuses:
*
* * **VALID**: control has passed all validation checks
* * **INVALID**: control has failed at least one validation check
* * **PENDING**: control is in the midst of conducting a validation check
* * **DISABLED**: control is exempt from validation checks
*
* These statuses are mutually exclusive, so a control cannot be
* both valid AND invalid or invalid AND disabled.
* @return {?}
*/
get: function () { return this._status; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "valid", {
/**
* A control is `valid` when its `status === VALID`.
*
* In order to have this status, the control must have passed all its
* validation checks.
* @return {?}
*/
get: function () { return this._status === VALID; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "invalid", {
/**
* A control is `invalid` when its `status === INVALID`.
*
* In order to have this status, the control must have failed
* at least one of its validation checks.
* @return {?}
*/
get: function () { return this._status === INVALID; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "pending", {
/**
* A control is `pending` when its `status === PENDING`.
*
* In order to have this status, the control must be in the
* middle of conducting a validation check.
* @return {?}
*/
get: function () { return this._status == PENDING; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "disabled", {
/**
* A control is `disabled` when its `status === DISABLED`.
*
* Disabled controls are exempt from validation checks and
* are not included in the aggregate value of their ancestor
* controls.
* @return {?}
*/
get: function () { return this._status === DISABLED; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "enabled", {
/**
* A control is `enabled` as long as its `status !== DISABLED`.
*
* In other words, it has a status of `VALID`, `INVALID`, or
* `PENDING`.
* @return {?}
*/
get: function () { return this._status !== DISABLED; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "errors", {
/**
* Returns any errors generated by failing validation. If there
* are no errors, it will return null.
* @return {?}
*/
get: function () { return this._errors; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "pristine", {
/**
* A control is `pristine` if the user has not yet changed
* the value in the UI.
*
* Note that programmatic changes to a control's value will
* *not* mark it dirty.
* @return {?}
*/
get: function () { return this._pristine; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "dirty", {
/**
* A control is `dirty` if the user has changed the value
* in the UI.
*
* Note that programmatic changes to a control's value will
* *not* mark it dirty.
* @return {?}
*/
get: function () { return !this.pristine; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "touched", {
/**
* A control is marked `touched` once the user has triggered
* a `blur` event on it.
* @return {?}
*/
get: function () { return this._touched; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "untouched", {
/**
* A control is `untouched` if the user has not yet triggered
* a `blur` event on it.
* @return {?}
*/
get: function () { return !this._touched; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "valueChanges", {
/**
* Emits an event every time the value of the control changes, in
* the UI or programmatically.
* @return {?}
*/
get: function () { return this._valueChanges; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "statusChanges", {
/**
* Emits an event every time the validation status of the control
* is re-calculated.
* @return {?}
*/
get: function () { return this._statusChanges; },
enumerable: true,
configurable: true
});
/**
* Sets the synchronous validators that are active on this control. Calling
* this will overwrite any existing sync validators.
* @param {?} newValidator
* @return {?}
*/
AbstractControl.prototype.setValidators = function (newValidator) {
this.validator = coerceToValidator(newValidator);
};
/**
* Sets the async validators that are active on this control. Calling this
* will overwrite any existing async validators.
* @param {?} newValidator
* @return {?}
*/
AbstractControl.prototype.setAsyncValidators = function (newValidator) {
this.asyncValidator = coerceToAsyncValidator(newValidator);
};
/**
* Empties out the sync validator list.
* @return {?}
*/
AbstractControl.prototype.clearValidators = function () { this.validator = null; };
/**
* Empties out the async validator list.
* @return {?}
*/
AbstractControl.prototype.clearAsyncValidators = function () { this.asyncValidator = null; };
/**
* Marks the control as `touched`.
*
* This will also mark all direct ancestors as `touched` to maintain
* the model.
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype.markAsTouched = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._touched = true;
if (this._parent && !onlySelf) {
this._parent.markAsTouched({ onlySelf: onlySelf });
}
};
/**
* Marks the control as `untouched`.
*
* If the control has any children, it will also mark all children as `untouched`
* to maintain the model, and re-calculate the `touched` status of all parent
* controls.
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype.markAsUntouched = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._touched = false;
this._forEachChild(function (control) { control.markAsUntouched({ onlySelf: true }); });
if (this._parent && !onlySelf) {
this._parent._updateTouched({ onlySelf: onlySelf });
}
};
/**
* Marks the control as `dirty`.
*
* This will also mark all direct ancestors as `dirty` to maintain
* the model.
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype.markAsDirty = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._pristine = false;
if (this._parent && !onlySelf) {
this._parent.markAsDirty({ onlySelf: onlySelf });
}
};
/**
* Marks the control as `pristine`.
*
* If the control has any children, it will also mark all children as `pristine`
* to maintain the model, and re-calculate the `pristine` status of all parent
* controls.
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype.markAsPristine = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._pristine = true;
this._forEachChild(function (control) { control.markAsPristine({ onlySelf: true }); });
if (this._parent && !onlySelf) {
this._parent._updatePristine({ onlySelf: onlySelf });
}
};
/**
* Marks the control as `pending`.
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype.markAsPending = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._status = PENDING;
if (this._parent && !onlySelf) {
this._parent.markAsPending({ onlySelf: onlySelf });
}
};
/**
* Disables the control. This means the control will be exempt from validation checks and
* excluded from the aggregate value of any parent. Its status is `DISABLED`.
*
* If the control has children, all children will be disabled to maintain the model.
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype.disable = function (_a) {
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._status = DISABLED;
this._errors = null;
this._forEachChild(function (control) { control.disable({ onlySelf: true }); });
this._updateValue();
if (emitEvent !== false) {
this._valueChanges.emit(this._value);
this._statusChanges.emit(this._status);
}
this._updateAncestors(!!onlySelf);
this._onDisabledChange.forEach(function (changeFn) { return changeFn(true); });
};
/**
* Enables the control. This means the control will be included in validation checks and
* the aggregate value of its parent. Its status is re-calculated based on its value and
* its validators.
*
* If the control has children, all children will be enabled.
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype.enable = function (_a) {
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._status = VALID;
this._forEachChild(function (control) { control.enable({ onlySelf: true }); });
this.updateValueAndValidity({ onlySelf: true, emitEvent: emitEvent });
this._updateAncestors(!!onlySelf);
this._onDisabledChange.forEach(function (changeFn) { return changeFn(false); });
};
/**
* @param {?} onlySelf
* @return {?}
*/
AbstractControl.prototype._updateAncestors = function (onlySelf) {
if (this._parent && !onlySelf) {
this._parent.updateValueAndValidity();
this._parent._updatePristine();
this._parent._updateTouched();
}
};
/**
* @param {?} parent
* @return {?}
*/
AbstractControl.prototype.setParent = function (parent) { this._parent = parent; };
/**
* Sets the value of the control. Abstract method (implemented in sub-classes).
* @abstract
* @param {?} value
* @param {?=} options
* @return {?}
*/
AbstractControl.prototype.setValue = function (value, options) { };
/**
* Patches the value of the control. Abstract method (implemented in sub-classes).
* @abstract
* @param {?} value
* @param {?=} options
* @return {?}
*/
AbstractControl.prototype.patchValue = function (value, options) { };
/**
* Resets the control. Abstract method (implemented in sub-classes).
* @abstract
* @param {?=} value
* @param {?=} options
* @return {?}
*/
AbstractControl.prototype.reset = function (value, options) { };
/**
* Re-calculates the value and validation status of the control.
*
* By default, it will also update the value and validity of its ancestors.
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype.updateValueAndValidity = function (_a) {
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._setInitialStatus();
this._updateValue();
if (this.enabled) {
this._cancelExistingSubscription();
this._errors = this._runValidator();
this._status = this._calculateStatus();
if (this._status === VALID || this._status === PENDING) {
this._runAsyncValidator(emitEvent);
}
}
if (emitEvent !== false) {
this._valueChanges.emit(this._value);
this._statusChanges.emit(this._status);
}
if (this._parent && !onlySelf) {
this._parent.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
}
};
/**
* \@internal
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype._updateTreeValidity = function (_a) {
var emitEvent = (_a === void 0 ? { emitEvent: true } : _a).emitEvent;
this._forEachChild(function (ctrl) { return ctrl._updateTreeValidity({ emitEvent: emitEvent }); });
this.updateValueAndValidity({ onlySelf: true, emitEvent: emitEvent });
};
/**
* @return {?}
*/
AbstractControl.prototype._setInitialStatus = function () { this._status = this._allControlsDisabled() ? DISABLED : VALID; };
/**
* @return {?}
*/
AbstractControl.prototype._runValidator = function () {
return this.validator ? this.validator(this) : null;
};
/**
* @param {?=} emitEvent
* @return {?}
*/
AbstractControl.prototype._runAsyncValidator = function (emitEvent) {
var _this = this;
if (this.asyncValidator) {
this._status = PENDING;
var /** @type {?} */ obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription =
obs.subscribe(function (errors) { return _this.setErrors(errors, { emitEvent: emitEvent }); });
}
};
/**
* @return {?}
*/
AbstractControl.prototype._cancelExistingSubscription = function () {
if (this._asyncValidationSubscription) {
this._asyncValidationSubscription.unsubscribe();
}
};
/**
* Sets errors on a form control.
*
* This is used when validations are run manually by the user, rather than automatically.
*
* Calling `setErrors` will also update the validity of the parent control.
*
* ### Example
*
* ```
* const login = new FormControl("someLogin");
* login.setErrors({
* "notUnique": true
* });
*
* expect(login.valid).toEqual(false);
* expect(login.errors).toEqual({"notUnique": true});
*
* login.setValue("someOtherLogin");
*
* expect(login.valid).toEqual(true);
* ```
* @param {?} errors
* @param {?=} __1
* @return {?}
*/
AbstractControl.prototype.setErrors = function (errors, _a) {
var emitEvent = (_a === void 0 ? {} : _a).emitEvent;
this._errors = errors;
this._updateControlsErrors(emitEvent !== false);
};
/**
* Retrieves a child control given the control's name or path.
*
* Paths can be passed in as an array or a string delimited by a dot.
*
* To get a control nested within a `person` sub-group:
*
* * `this.form.get('person.name');`
*
* -OR-
*
* * `this.form.get(['person', 'name']);`
* @param {?} path
* @return {?}
*/
AbstractControl.prototype.get = function (path) { return _find(this, path, '.'); };
/**
* Returns true if the control with the given path has the error specified. Otherwise
* returns null or undefined.
*
* If no path is given, it checks for the error on the present control.
* @param {?} errorCode
* @param {?=} path
* @return {?}
*/
AbstractControl.prototype.getError = function (errorCode, path) {
var /** @type {?} */ control = path ? this.get(path) : this;
return control && control._errors ? control._errors[errorCode] : null;
};
/**
* Returns true if the control with the given path has the error specified. Otherwise
* returns false.
*
* If no path is given, it checks for the error on the present control.
* @param {?} errorCode
* @param {?=} path
* @return {?}
*/
AbstractControl.prototype.hasError = function (errorCode, path) { return !!this.getError(errorCode, path); };
Object.defineProperty(AbstractControl.prototype, "root", {
/**
* Retrieves the top-level ancestor of this control.
* @return {?}
*/
get: function () {
var /** @type {?} */ x = this;
while (x._parent) {
x = x._parent;
}
return x;
},
enumerable: true,
configurable: true
});
/**
* \@internal
* @param {?} emitEvent
* @return {?}
*/
AbstractControl.prototype._updateControlsErrors = function (emitEvent) {
this._status = this._calculateStatus();
if (emitEvent) {
this._statusChanges.emit(this._status);
}
if (this._parent) {
this._parent._updateControlsErrors(emitEvent);
}
};
/**
* \@internal
* @return {?}
*/
AbstractControl.prototype._initObservables = function () {
this._valueChanges = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["r" /* EventEmitter */]();
this._statusChanges = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["r" /* EventEmitter */]();
};
/**
* @return {?}
*/
AbstractControl.prototype._calculateStatus = function () {
if (this._allControlsDisabled())
return DISABLED;
if (this._errors)
return INVALID;
if (this._anyControlsHaveStatus(PENDING))
return PENDING;
if (this._anyControlsHaveStatus(INVALID))
return INVALID;
return VALID;
};
/**
* \@internal
* @abstract
* @return {?}
*/
AbstractControl.prototype._updateValue = function () { };
/**
* \@internal
* @abstract
* @param {?} cb
* @return {?}
*/
AbstractControl.prototype._forEachChild = function (cb) { };
/**
* \@internal
* @abstract
* @param {?} condition
* @return {?}
*/
AbstractControl.prototype._anyControls = function (condition) { };
/**
* \@internal
* @abstract
* @return {?}
*/
AbstractControl.prototype._allControlsDisabled = function () { };
/**
* \@internal
* @param {?} status
* @return {?}
*/
AbstractControl.prototype._anyControlsHaveStatus = function (status) {
return this._anyControls(function (control) { return control.status === status; });
};
/**
* \@internal
* @return {?}
*/
AbstractControl.prototype._anyControlsDirty = function () {
return this._anyControls(function (control) { return control.dirty; });
};
/**
* \@internal
* @return {?}
*/
AbstractControl.prototype._anyControlsTouched = function () {
return this._anyControls(function (control) { return control.touched; });
};
/**
* \@internal
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype._updatePristine = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._pristine = !this._anyControlsDirty();
if (this._parent && !onlySelf) {
this._parent._updatePristine({ onlySelf: onlySelf });
}
};
/**
* \@internal
* @param {?=} __0
* @return {?}
*/
AbstractControl.prototype._updateTouched = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._touched = this._anyControlsTouched();
if (this._parent && !onlySelf) {
this._parent._updateTouched({ onlySelf: onlySelf });
}
};
/**
* \@internal
* @param {?} formState
* @return {?}
*/
AbstractControl.prototype._isBoxedValue = function (formState) {
return typeof formState === 'object' && formState !== null &&
Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState;
};
/**
* \@internal
* @param {?} fn
* @return {?}
*/
AbstractControl.prototype._registerOnCollectionChange = function (fn) { this._onCollectionChange = fn; };
return AbstractControl;
}());
/**
* \@whatItDoes Tracks the value and validation status of an individual form control.
*
* It is one of the three fundamental building blocks of Angular forms, along with
* {\@link FormGroup} and {\@link FormArray}.
*
* \@howToUse
*
* When instantiating a {\@link FormControl}, you can pass in an initial value as the
* first argument. Example:
*
* ```ts
* const ctrl = new FormControl('some value');
* console.log(ctrl.value); // 'some value'
* ```
*
* You can also initialize the control with a form state object on instantiation,
* which includes both the value and whether or not the control is disabled.
* You can't use the value key without the disabled key; both are required
* to use this way of initialization.
*
* ```ts
* const ctrl = new FormControl({value: 'n/a', disabled: true});
* console.log(ctrl.value); // 'n/a'
* console.log(ctrl.status); // 'DISABLED'
* ```
*
* To include a sync validator (or an array of sync validators) with the control,
* pass it in as the second argument. Async validators are also supported, but
* have to be passed in separately as the third arg.
*
* ```ts
* const ctrl = new FormControl('', Validators.required);
* console.log(ctrl.value); // ''
* console.log(ctrl.status); // 'INVALID'
* ```
*
* See its superclass, {\@link AbstractControl}, for more properties and methods.
*
* * **npm package**: `\@angular/forms`
*
* \@stable
*/
var FormControl = (function (_super) {
__extends(FormControl, _super);
/**
* @param {?=} formState
* @param {?=} validator
* @param {?=} asyncValidator
*/
function FormControl(formState, validator, asyncValidator) {
if (formState === void 0) { formState = null; }
var _this = _super.call(this, coerceToValidator(validator), coerceToAsyncValidator(asyncValidator)) || this;
/**
* \@internal
*/
_this._onChange = [];
_this._applyFormState(formState);
_this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
_this._initObservables();
return _this;
}
/**
* Set the value of the form control to `value`.
*
* If `onlySelf` is `true`, this change will only affect the validation of this `FormControl`
* and not its parent component. This defaults to false.
*
* If `emitEvent` is `true`, this
* change will cause a `valueChanges` event on the `FormControl` to be emitted. This defaults
* to true (as it falls through to `updateValueAndValidity`).
*
* If `emitModelToViewChange` is `true`, the view will be notified about the new value
* via an `onChange` event. This is the default behavior if `emitModelToViewChange` is not
* specified.
*
* If `emitViewToModelChange` is `true`, an ngModelChange event will be fired to update the
* model. This is the default behavior if `emitViewToModelChange` is not specified.
* @param {?} value
* @param {?=} options
* @return {?}
*/
FormControl.prototype.setValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
this._value = value;
if (this._onChange.length && options.emitModelToViewChange !== false) {
this._onChange.forEach(function (changeFn) { return changeFn(_this._value, options.emitViewToModelChange !== false); });
}
this.updateValueAndValidity(options);
};
/**
* Patches the value of a control.
*
* This function is functionally the same as {\@link FormControl.setValue} at this level.
* It exists for symmetry with {\@link FormGroup.patchValue} on `FormGroups` and `FormArrays`,
* where it does behave differently.
* @param {?} value
* @param {?=} options
* @return {?}
*/
FormControl.prototype.patchValue = function (value, options) {
if (options === void 0) { options = {}; }
this.setValue(value, options);
};
/**
* Resets the form control. This means by default:
*
* * it is marked as `pristine`
* * it is marked as `untouched`
* * value is set to null
*
* You can also reset to a specific form state by passing through a standalone
* value or a form state object that contains both a value and a disabled state
* (these are the only two properties that cannot be calculated).
*
* Ex:
*
* ```ts
* this.control.reset('Nancy');
*
* console.log(this.control.value); // 'Nancy'
* ```
*
* OR
*
* ```
* this.control.reset({value: 'Nancy', disabled: true});
*
* console.log(this.control.value); // 'Nancy'
* console.log(this.control.status); // 'DISABLED'
* ```
* @param {?=} formState
* @param {?=} options
* @return {?}
*/
FormControl.prototype.reset = function (formState, options) {
if (formState === void 0) { formState = null; }
if (options === void 0) { options = {}; }
this._applyFormState(formState);
this.markAsPristine(options);
this.markAsUntouched(options);
this.setValue(this._value, options);
};
/**
* \@internal
* @return {?}
*/
FormControl.prototype._updateValue = function () { };
/**
* \@internal
* @param {?} condition
* @return {?}
*/
FormControl.prototype._anyControls = function (condition) { return false; };
/**
* \@internal
* @return {?}
*/
FormControl.prototype._allControlsDisabled = function () { return this.disabled; };
/**
* Register a listener for change events.
* @param {?} fn
* @return {?}
*/
FormControl.prototype.registerOnChange = function (fn) { this._onChange.push(fn); };
/**
* \@internal
* @return {?}
*/
FormControl.prototype._clearChangeFns = function () {
this._onChange = [];
this._onDisabledChange = [];
this._onCollectionChange = function () { };
};
/**
* Register a listener for disabled events.
* @param {?} fn
* @return {?}
*/
FormControl.prototype.registerOnDisabledChange = function (fn) {
this._onDisabledChange.push(fn);
};
/**
* \@internal
* @param {?} cb
* @return {?}
*/
FormControl.prototype._forEachChild = function (cb) { };
/**
* @param {?} formState
* @return {?}
*/
FormControl.prototype._applyFormState = function (formState) {
if (this._isBoxedValue(formState)) {
this._value = formState.value;
formState.disabled ? this.disable({ onlySelf: true, emitEvent: false }) :
this.enable({ onlySelf: true, emitEvent: false });
}
else {
this._value = formState;
}
};
return FormControl;
}(AbstractControl));
/**
* \@whatItDoes Tracks the value and validity state of a group of {\@link FormControl}
* instances.
*
* A `FormGroup` aggregates the values of each child {\@link FormControl} into one object,
* with each control name as the key. It calculates its status by reducing the statuses
* of its children. For example, if one of the controls in a group is invalid, the entire
* group becomes invalid.
*
* `FormGroup` is one of the three fundamental building blocks used to define forms in Angular,
* along with {\@link FormControl} and {\@link FormArray}.
*
* \@howToUse
*
* When instantiating a {\@link FormGroup}, pass in a collection of child controls as the first
* argument. The key for each child will be the name under which it is registered.
*
* ### Example
*
* ```
* const form = new FormGroup({
* first: new FormControl('Nancy', Validators.minLength(2)),
* last: new FormControl('Drew'),
* });
*
* console.log(form.value); // {first: 'Nancy', last; 'Drew'}
* console.log(form.status); // 'VALID'
* ```
*
* You can also include group-level validators as the second arg, or group-level async
* validators as the third arg. These come in handy when you want to perform validation
* that considers the value of more than one child control.
*
* ### Example
*
* ```
* const form = new FormGroup({
* password: new FormControl('', Validators.minLength(2)),
* passwordConfirm: new FormControl('', Validators.minLength(2)),
* }, passwordMatchValidator);
*
*
* function passwordMatchValidator(g: FormGroup) {
* return g.get('password').value === g.get('passwordConfirm').value
* ? null : {'mismatch': true};
* }
* ```
*
* * **npm package**: `\@angular/forms`
*
* \@stable
*/
var FormGroup = (function (_super) {
__extends(FormGroup, _super);
/**
* @param {?} controls
* @param {?=} validator
* @param {?=} asyncValidator
*/
function FormGroup(controls, validator, asyncValidator) {
var _this = _super.call(this, validator || null, asyncValidator || null) || this;
_this.controls = controls;
_this._initObservables();
_this._setUpControls();
_this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
return _this;
}
/**
* Registers a control with the group's list of controls.
*
* This method does not update value or validity of the control, so for
* most cases you'll want to use {\@link FormGroup.addControl} instead.
* @param {?} name
* @param {?} control
* @return {?}
*/
FormGroup.prototype.registerControl = function (name, control) {
if (this.controls[name])
return this.controls[name];
this.controls[name] = control;
control.setParent(this);
control._registerOnCollectionChange(this._onCollectionChange);
return control;
};
/**
* Add a control to this group.
* @param {?} name
* @param {?} control
* @return {?}
*/
FormGroup.prototype.addControl = function (name, control) {
this.registerControl(name, control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Remove a control from this group.
* @param {?} name
* @return {?}
*/
FormGroup.prototype.removeControl = function (name) {
if (this.controls[name])
this.controls[name]._registerOnCollectionChange(function () { });
delete (this.controls[name]);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Replace an existing control.
* @param {?} name
* @param {?} control
* @return {?}
*/
FormGroup.prototype.setControl = function (name, control) {
if (this.controls[name])
this.controls[name]._registerOnCollectionChange(function () { });
delete (this.controls[name]);
if (control)
this.registerControl(name, control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Check whether there is an enabled control with the given name in the group.
*
* It will return false for disabled controls. If you'd like to check for
* existence in the group only, use {\@link AbstractControl#get} instead.
* @param {?} controlName
* @return {?}
*/
FormGroup.prototype.contains = function (controlName) {
return this.controls.hasOwnProperty(controlName) && this.controls[controlName].enabled;
};
/**
* Sets the value of the {\@link FormGroup}. It accepts an object that matches
* the structure of the group, with control names as keys.
*
* This method performs strict checks, so it will throw an error if you try
* to set the value of a control that doesn't exist or if you exclude the
* value of a control.
*
* ### Example
*
* ```
* const form = new FormGroup({
* first: new FormControl(),
* last: new FormControl()
* });
* console.log(form.value); // {first: null, last: null}
*
* form.setValue({first: 'Nancy', last: 'Drew'});
* console.log(form.value); // {first: 'Nancy', last: 'Drew'}
*
* ```
* @param {?} value
* @param {?=} options
* @return {?}
*/
FormGroup.prototype.setValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
this._checkAllValuesPresent(value);
Object.keys(value).forEach(function (name) {
_this._throwIfControlMissing(name);
_this.controls[name].setValue(value[name], { onlySelf: true, emitEvent: options.emitEvent });
});
this.updateValueAndValidity(options);
};
/**
* Patches the value of the {\@link FormGroup}. It accepts an object with control
* names as keys, and will do its best to match the values to the correct controls
* in the group.
*
* It accepts both super-sets and sub-sets of the group without throwing an error.
*
* ### Example
*
* ```
* const form = new FormGroup({
* first: new FormControl(),
* last: new FormControl()
* });
* console.log(form.value); // {first: null, last: null}
*
* form.patchValue({first: 'Nancy'});
* console.log(form.value); // {first: 'Nancy', last: null}
*
* ```
* @param {?} value
* @param {?=} options
* @return {?}
*/
FormGroup.prototype.patchValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
Object.keys(value).forEach(function (name) {
if (_this.controls[name]) {
_this.controls[name].patchValue(value[name], { onlySelf: true, emitEvent: options.emitEvent });
}
});
this.updateValueAndValidity(options);
};
/**
* Resets the {\@link FormGroup}. This means by default:
*
* * The group and all descendants are marked `pristine`
* * The group and all descendants are marked `untouched`
* * The value of all descendants will be null or null maps
*
* You can also reset to a specific form state by passing in a map of states
* that matches the structure of your form, with control names as keys. The state
* can be a standalone value or a form state object with both a value and a disabled
* status.
*
* ### Example
*
* ```ts
* this.form.reset({first: 'name', last: 'last name'});
*
* console.log(this.form.value); // {first: 'name', last: 'last name'}
* ```
*
* - OR -
*
* ```
* this.form.reset({
* first: {value: 'name', disabled: true},
* last: 'last'
* });
*
* console.log(this.form.value); // {first: 'name', last: 'last name'}
* console.log(this.form.get('first').status); // 'DISABLED'
* ```
* @param {?=} value
* @param {?=} options
* @return {?}
*/
FormGroup.prototype.reset = function (value, options) {
if (value === void 0) { value = {}; }
if (options === void 0) { options = {}; }
this._forEachChild(function (control, name) {
control.reset(value[name], { onlySelf: true, emitEvent: options.emitEvent });
});
this.updateValueAndValidity(options);
this._updatePristine(options);
this._updateTouched(options);
};
/**
* The aggregate value of the {\@link FormGroup}, including any disabled controls.
*
* If you'd like to include all values regardless of disabled status, use this method.
* Otherwise, the `value` property is the best way to get the value of the group.
* @return {?}
*/
FormGroup.prototype.getRawValue = function () {
return this._reduceChildren({}, function (acc, control, name) {
acc[name] = control instanceof FormControl ? control.value : ((control)).getRawValue();
return acc;
});
};
/**
* \@internal
* @param {?} name
* @return {?}
*/
FormGroup.prototype._throwIfControlMissing = function (name) {
if (!Object.keys(this.controls).length) {
throw new Error("\n There are no form controls registered with this group yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");
}
if (!this.controls[name]) {
throw new Error("Cannot find form control with name: " + name + ".");
}
};
/**
* \@internal
* @param {?} cb
* @return {?}
*/
FormGroup.prototype._forEachChild = function (cb) {
var _this = this;
Object.keys(this.controls).forEach(function (k) { return cb(_this.controls[k], k); });
};
/**
* \@internal
* @return {?}
*/
FormGroup.prototype._setUpControls = function () {
var _this = this;
this._forEachChild(function (control) {
control.setParent(_this);
control._registerOnCollectionChange(_this._onCollectionChange);
});
};
/**
* \@internal
* @return {?}
*/
FormGroup.prototype._updateValue = function () { this._value = this._reduceValue(); };
/**
* \@internal
* @param {?} condition
* @return {?}
*/
FormGroup.prototype._anyControls = function (condition) {
var _this = this;
var /** @type {?} */ res = false;
this._forEachChild(function (control, name) {
res = res || (_this.contains(name) && condition(control));
});
return res;
};
/**
* \@internal
* @return {?}
*/
FormGroup.prototype._reduceValue = function () {
var _this = this;
return this._reduceChildren({}, function (acc, control, name) {
if (control.enabled || _this.disabled) {
acc[name] = control.value;
}
return acc;
});
};
/**
* \@internal
* @param {?} initValue
* @param {?} fn
* @return {?}
*/
FormGroup.prototype._reduceChildren = function (initValue, fn) {
var /** @type {?} */ res = initValue;
this._forEachChild(function (control, name) { res = fn(res, control, name); });
return res;
};
/**
* \@internal
* @return {?}
*/
FormGroup.prototype._allControlsDisabled = function () {
for (var _i = 0, _a = Object.keys(this.controls); _i < _a.length; _i++) {
var controlName = _a[_i];
if (this.controls[controlName].enabled) {
return false;
}
}
return Object.keys(this.controls).length > 0 || this.disabled;
};
/**
* \@internal
* @param {?} value
* @return {?}
*/
FormGroup.prototype._checkAllValuesPresent = function (value) {
this._forEachChild(function (control, name) {
if (value[name] === undefined) {
throw new Error("Must supply a value for form control with name: '" + name + "'.");
}
});
};
return FormGroup;
}(AbstractControl));
/**
* \@whatItDoes Tracks the value and validity state of an array of {\@link FormControl},
* {\@link FormGroup} or {\@link FormArray} instances.
*
* A `FormArray` aggregates the values of each child {\@link FormControl} into an array.
* It calculates its status by reducing the statuses of its children. For example, if one of
* the controls in a `FormArray` is invalid, the entire array becomes invalid.
*
* `FormArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with {\@link FormControl} and {\@link FormGroup}.
*
* \@howToUse
*
* When instantiating a {\@link FormArray}, pass in an array of child controls as the first
* argument.
*
* ### Example
*
* ```
* const arr = new FormArray([
* new FormControl('Nancy', Validators.minLength(2)),
* new FormControl('Drew'),
* ]);
*
* console.log(arr.value); // ['Nancy', 'Drew']
* console.log(arr.status); // 'VALID'
* ```
*
* You can also include array-level validators as the second arg, or array-level async
* validators as the third arg. These come in handy when you want to perform validation
* that considers the value of more than one child control.
*
* ### Adding or removing controls
*
* To change the controls in the array, use the `push`, `insert`, or `removeAt` methods
* in `FormArray` itself. These methods ensure the controls are properly tracked in the
* form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
* the `FormArray` directly, as that will result in strange and unexpected behavior such
* as broken change detection.
*
* * **npm package**: `\@angular/forms`
*
* \@stable
*/
var FormArray = (function (_super) {
__extends(FormArray, _super);
/**
* @param {?} controls
* @param {?=} validator
* @param {?=} asyncValidator
*/
function FormArray(controls, validator, asyncValidator) {
var _this = _super.call(this, validator || null, asyncValidator || null) || this;
_this.controls = controls;
_this._initObservables();
_this._setUpControls();
_this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
return _this;
}
/**
* Get the {\@link AbstractControl} at the given `index` in the array.
* @param {?} index
* @return {?}
*/
FormArray.prototype.at = function (index) { return this.controls[index]; };
/**
* Insert a new {\@link AbstractControl} at the end of the array.
* @param {?} control
* @return {?}
*/
FormArray.prototype.push = function (control) {
this.controls.push(control);
this._registerControl(control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Insert a new {\@link AbstractControl} at the given `index` in the array.
* @param {?} index
* @param {?} control
* @return {?}
*/
FormArray.prototype.insert = function (index, control) {
this.controls.splice(index, 0, control);
this._registerControl(control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Remove the control at the given `index` in the array.
* @param {?} index
* @return {?}
*/
FormArray.prototype.removeAt = function (index) {
if (this.controls[index])
this.controls[index]._registerOnCollectionChange(function () { });
this.controls.splice(index, 1);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Replace an existing control.
* @param {?} index
* @param {?} control
* @return {?}
*/
FormArray.prototype.setControl = function (index, control) {
if (this.controls[index])
this.controls[index]._registerOnCollectionChange(function () { });
this.controls.splice(index, 1);
if (control) {
this.controls.splice(index, 0, control);
this._registerControl(control);
}
this.updateValueAndValidity();
this._onCollectionChange();
};
Object.defineProperty(FormArray.prototype, "length", {
/**
* Length of the control array.
* @return {?}
*/
get: function () { return this.controls.length; },
enumerable: true,
configurable: true
});
/**
* Sets the value of the {\@link FormArray}. It accepts an array that matches
* the structure of the control.
*
* This method performs strict checks, so it will throw an error if you try
* to set the value of a control that doesn't exist or if you exclude the
* value of a control.
*
* ### Example
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.setValue(['Nancy', 'Drew']);
* console.log(arr.value); // ['Nancy', 'Drew']
* ```
* @param {?} value
* @param {?=} options
* @return {?}
*/
FormArray.prototype.setValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
this._checkAllValuesPresent(value);
value.forEach(function (newValue, index) {
_this._throwIfControlMissing(index);
_this.at(index).setValue(newValue, { onlySelf: true, emitEvent: options.emitEvent });
});
this.updateValueAndValidity(options);
};
/**
* Patches the value of the {\@link FormArray}. It accepts an array that matches the
* structure of the control, and will do its best to match the values to the correct
* controls in the group.
*
* It accepts both super-sets and sub-sets of the array without throwing an error.
*
* ### Example
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.patchValue(['Nancy']);
* console.log(arr.value); // ['Nancy', null]
* ```
* @param {?} value
* @param {?=} options
* @return {?}
*/
FormArray.prototype.patchValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
value.forEach(function (newValue, index) {
if (_this.at(index)) {
_this.at(index).patchValue(newValue, { onlySelf: true, emitEvent: options.emitEvent });
}
});
this.updateValueAndValidity(options);
};
/**
* Resets the {\@link FormArray}. This means by default:
*
* * The array and all descendants are marked `pristine`
* * The array and all descendants are marked `untouched`
* * The value of all descendants will be null or null maps
*
* You can also reset to a specific form state by passing in an array of states
* that matches the structure of the control. The state can be a standalone value
* or a form state object with both a value and a disabled status.
*
* ### Example
*
* ```ts
* this.arr.reset(['name', 'last name']);
*
* console.log(this.arr.value); // ['name', 'last name']
* ```
*
* - OR -
*
* ```
* this.arr.reset([
* {value: 'name', disabled: true},
* 'last'
* ]);
*
* console.log(this.arr.value); // ['name', 'last name']
* console.log(this.arr.get(0).status); // 'DISABLED'
* ```
* @param {?=} value
* @param {?=} options
* @return {?}
*/
FormArray.prototype.reset = function (value, options) {
if (value === void 0) { value = []; }
if (options === void 0) { options = {}; }
this._forEachChild(function (control, index) {
control.reset(value[index], { onlySelf: true, emitEvent: options.emitEvent });
});
this.updateValueAndValidity(options);
this._updatePristine(options);
this._updateTouched(options);
};
/**
* The aggregate value of the array, including any disabled controls.
*
* If you'd like to include all values regardless of disabled status, use this method.
* Otherwise, the `value` property is the best way to get the value of the array.
* @return {?}
*/
FormArray.prototype.getRawValue = function () {
return this.controls.map(function (control) {
return control instanceof FormControl ? control.value : ((control)).getRawValue();
});
};
/**
* \@internal
* @param {?} index
* @return {?}
*/
FormArray.prototype._throwIfControlMissing = function (index) {
if (!this.controls.length) {
throw new Error("\n There are no form controls registered with this array yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");
}
if (!this.at(index)) {
throw new Error("Cannot find form control at index " + index);
}
};
/**
* \@internal
* @param {?} cb
* @return {?}
*/
FormArray.prototype._forEachChild = function (cb) {
this.controls.forEach(function (control, index) { cb(control, index); });
};
/**
* \@internal
* @return {?}
*/
FormArray.prototype._updateValue = function () {
var _this = this;
this._value = this.controls.filter(function (control) { return control.enabled || _this.disabled; })
.map(function (control) { return control.value; });
};
/**
* \@internal
* @param {?} condition
* @return {?}
*/
FormArray.prototype._anyControls = function (condition) {
return this.controls.some(function (control) { return control.enabled && condition(control); });
};
/**
* \@internal
* @return {?}
*/
FormArray.prototype._setUpControls = function () {
var _this = this;
this._forEachChild(function (control) { return _this._registerControl(control); });
};
/**
* \@internal
* @param {?} value
* @return {?}
*/
FormArray.prototype._checkAllValuesPresent = function (value) {
this._forEachChild(function (control, i) {
if (value[i] === undefined) {
throw new Error("Must supply a value for form control at index: " + i + ".");
}
});
};
/**
* \@internal
* @return {?}
*/
FormArray.prototype._allControlsDisabled = function () {
for (var _i = 0, _a = this.controls; _i < _a.length; _i++) {
var control = _a[_i];
if (control.enabled)
return false;
}
return this.controls.length > 0 || this.disabled;
};
/**
* @param {?} control
* @return {?}
*/
FormArray.prototype._registerControl = function (control) {
control.setParent(this);
control._registerOnCollectionChange(this._onCollectionChange);
};
return FormArray;
}(AbstractControl));
/**
* @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
*/
var formDirectiveProvider = {
provide: ControlContainer,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return NgForm; })
};
var resolvedPromise = Promise.resolve(null);
/**
* \@whatItDoes Creates a top-level {\@link FormGroup} instance and binds it to a form
* to track aggregate form value and validation status.
*
* \@howToUse
*
* As soon as you import the `FormsModule`, this directive becomes active by default on
* all `<form>` tags. You don't need to add a special selector.
*
* You can export the directive into a local template variable using `ngForm` as the key
* (ex: `#myForm="ngForm"`). This is optional, but useful. Many properties from the underlying
* {\@link FormGroup} instance are duplicated on the directive itself, so a reference to it
* will give you access to the aggregate value and validity status of the form, as well as
* user interaction properties like `dirty` and `touched`.
*
* To register child controls with the form, you'll want to use {\@link NgModel} with a
* `name` attribute. You can also use {\@link NgModelGroup} if you'd like to create
* sub-groups within the form.
*
* You can listen to the directive's `ngSubmit` event to be notified when the user has
* triggered a form submission. The `ngSubmit` event will be emitted with the original form
* submission event.
*
* {\@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
*
* * **npm package**: `\@angular/forms`
*
* * **NgModule**: `FormsModule`
*
* \@stable
*/
var NgForm = (function (_super) {
__extends(NgForm, _super);
/**
* @param {?} validators
* @param {?} asyncValidators
*/
function NgForm(validators, asyncValidators) {
var _this = _super.call(this) || this;
_this._submitted = false;
_this.ngSubmit = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["r" /* EventEmitter */]();
_this.form =
new FormGroup({}, composeValidators(validators), composeAsyncValidators(asyncValidators));
return _this;
}
Object.defineProperty(NgForm.prototype, "submitted", {
/**
* @return {?}
*/
get: function () { return this._submitted; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "formDirective", {
/**
* @return {?}
*/
get: function () { return this; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "control", {
/**
* @return {?}
*/
get: function () { return this.form; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "path", {
/**
* @return {?}
*/
get: function () { return []; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "controls", {
/**
* @return {?}
*/
get: function () { return this.form.controls; },
enumerable: true,
configurable: true
});
/**
* @param {?} dir
* @return {?}
*/
NgForm.prototype.addControl = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var /** @type {?} */ container = _this._findContainer(dir.path);
dir._control = (container.registerControl(dir.name, dir.control));
setUpControl(dir.control, dir);
dir.control.updateValueAndValidity({ emitEvent: false });
});
};
/**
* @param {?} dir
* @return {?}
*/
NgForm.prototype.getControl = function (dir) { return (this.form.get(dir.path)); };
/**
* @param {?} dir
* @return {?}
*/
NgForm.prototype.removeControl = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var /** @type {?} */ container = _this._findContainer(dir.path);
if (container) {
container.removeControl(dir.name);
}
});
};
/**
* @param {?} dir
* @return {?}
*/
NgForm.prototype.addFormGroup = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var /** @type {?} */ container = _this._findContainer(dir.path);
var /** @type {?} */ group = new FormGroup({});
setUpFormContainer(group, dir);
container.registerControl(dir.name, group);
group.updateValueAndValidity({ emitEvent: false });
});
};
/**
* @param {?} dir
* @return {?}
*/
NgForm.prototype.removeFormGroup = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var /** @type {?} */ container = _this._findContainer(dir.path);
if (container) {
container.removeControl(dir.name);
}
});
};
/**
* @param {?} dir
* @return {?}
*/
NgForm.prototype.getFormGroup = function (dir) { return (this.form.get(dir.path)); };
/**
* @param {?} dir
* @param {?} value
* @return {?}
*/
NgForm.prototype.updateModel = function (dir, value) {
var _this = this;
resolvedPromise.then(function () {
var /** @type {?} */ ctrl = (_this.form.get(/** @type {?} */ ((dir.path))));
ctrl.setValue(value);
});
};
/**
* @param {?} value
* @return {?}
*/
NgForm.prototype.setValue = function (value) { this.control.setValue(value); };
/**
* @param {?} $event
* @return {?}
*/
NgForm.prototype.onSubmit = function ($event) {
this._submitted = true;
this.ngSubmit.emit($event);
return false;
};
/**
* @return {?}
*/
NgForm.prototype.onReset = function () { this.resetForm(); };
/**
* @param {?=} value
* @return {?}
*/
NgForm.prototype.resetForm = function (value) {
if (value === void 0) { value = undefined; }
this.form.reset(value);
this._submitted = false;
};
/**
* \@internal
* @param {?} path
* @return {?}
*/
NgForm.prototype._findContainer = function (path) {
path.pop();
return path.length ? (this.form.get(path)) : this.form;
};
return NgForm;
}(ControlContainer));
NgForm.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'form:not([ngNoForm]):not([formGroup]),ngForm,[ngForm]',
providers: [formDirectiveProvider],
host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' },
outputs: ['ngSubmit'],
exportAs: 'ngForm'
},] },
];
/**
* @nocollapse
*/
NgForm.ctorParameters = function () { return [
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_ASYNC_VALIDATORS,] },] },
]; };
/**
* @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
*/
var FormErrorExamples = {
formControlName: "\n <div [formGroup]=\"myGroup\">\n <input formControlName=\"firstName\">\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n firstName: new FormControl()\n });",
formGroupName: "\n <div [formGroup]=\"myGroup\">\n <div formGroupName=\"person\">\n <input formControlName=\"firstName\">\n </div>\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n person: new FormGroup({ firstName: new FormControl() })\n });",
formArrayName: "\n <div [formGroup]=\"myGroup\">\n <div formArrayName=\"cities\">\n <div *ngFor=\"let city of cityArray.controls; index as i\">\n <input [formControlName]=\"i\">\n </div>\n </div>\n </div>\n\n In your class:\n\n this.cityArray = new FormArray([new FormControl('SF')]);\n this.myGroup = new FormGroup({\n cities: this.cityArray\n });",
ngModelGroup: "\n <form>\n <div ngModelGroup=\"person\">\n <input [(ngModel)]=\"person.name\" name=\"firstName\">\n </div>\n </form>",
ngModelWithFormGroup: "\n <div [formGroup]=\"myGroup\">\n <input formControlName=\"firstName\">\n <input [(ngModel)]=\"showMoreControls\" [ngModelOptions]=\"{standalone: true}\">\n </div>\n "
};
/**
* @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
*/
var TemplateDrivenErrors = (function () {
function TemplateDrivenErrors() {
}
/**
* @return {?}
*/
TemplateDrivenErrors.modelParentException = function () {
throw new Error("\n ngModel cannot be used to register form controls with a parent formGroup directive. Try using\n formGroup's partner directive \"formControlName\" instead. Example:\n\n " + FormErrorExamples.formControlName + "\n\n Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:\n\n Example:\n\n " + FormErrorExamples.ngModelWithFormGroup);
};
/**
* @return {?}
*/
TemplateDrivenErrors.formGroupNameException = function () {
throw new Error("\n ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.\n\n Option 1: Use formControlName instead of ngModel (reactive strategy):\n\n " + FormErrorExamples.formGroupName + "\n\n Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):\n\n " + FormErrorExamples.ngModelGroup);
};
/**
* @return {?}
*/
TemplateDrivenErrors.missingNameException = function () {
throw new Error("If ngModel is used within a form tag, either the name attribute must be set or the form\n control must be defined as 'standalone' in ngModelOptions.\n\n Example 1: <input [(ngModel)]=\"person.firstName\" name=\"first\">\n Example 2: <input [(ngModel)]=\"person.firstName\" [ngModelOptions]=\"{standalone: true}\">");
};
/**
* @return {?}
*/
TemplateDrivenErrors.modelGroupParentException = function () {
throw new Error("\n ngModelGroup cannot be used with a parent formGroup directive.\n\n Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):\n\n " + FormErrorExamples.formGroupName + "\n\n Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):\n\n " + FormErrorExamples.ngModelGroup);
};
return TemplateDrivenErrors;
}());
/**
* @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
*/
var modelGroupProvider = {
provide: ControlContainer,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return NgModelGroup; })
};
/**
* \@whatItDoes Creates and binds a {\@link FormGroup} instance to a DOM element.
*
* \@howToUse
*
* This directive can only be used as a child of {\@link NgForm} (or in other words,
* within `<form>` tags).
*
* Use this directive if you'd like to create a sub-group within a form. This can
* come in handy if you want to validate a sub-group of your form separately from
* the rest of your form, or if some values in your domain model make more sense to
* consume together in a nested object.
*
* Pass in the name you'd like this sub-group to have and it will become the key
* for the sub-group in the form's full value. You can also export the directive into
* a local template variable using `ngModelGroup` (ex: `#myGroup="ngModelGroup"`).
*
* {\@example forms/ts/ngModelGroup/ng_model_group_example.ts region='Component'}
*
* * **npm package**: `\@angular/forms`
*
* * **NgModule**: `FormsModule`
*
* \@stable
*/
var NgModelGroup = (function (_super) {
__extends(NgModelGroup, _super);
/**
* @param {?} parent
* @param {?} validators
* @param {?} asyncValidators
*/
function NgModelGroup(parent, validators, asyncValidators) {
var _this = _super.call(this) || this;
_this._parent = parent;
_this._validators = validators;
_this._asyncValidators = asyncValidators;
return _this;
}
/**
* \@internal
* @return {?}
*/
NgModelGroup.prototype._checkParentType = function () {
if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) {
TemplateDrivenErrors.modelGroupParentException();
}
};
return NgModelGroup;
}(AbstractFormGroupDirective));
NgModelGroup.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngModelGroup]', providers: [modelGroupProvider], exportAs: 'ngModelGroup' },] },
];
/**
* @nocollapse
*/
NgModelGroup.ctorParameters = function () { return [
{ type: ControlContainer, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["s" /* SkipSelf */] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_ASYNC_VALIDATORS,] },] },
]; };
NgModelGroup.propDecorators = {
'name': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['ngModelGroup',] },],
};
/**
* @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
*/
var formControlBinding = {
provide: NgControl,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return NgModel; })
};
/**
* `ngModel` forces an additional change detection run when its inputs change:
* E.g.:
* ```
* <div>{{myModel.valid}}</div>
* <input [(ngModel)]="myValue" #myModel="ngModel">
* ```
* I.e. `ngModel` can export itself on the element and then be used in the template.
* Normally, this would result in expressions before the `input` that use the exported directive
* to have and old value as they have been
* dirty checked before. As this is a very common case for `ngModel`, we added this second change
* detection run.
*
* Notes:
* - this is just one extra run no matter how many `ngModel` have been changed.
* - this is a general problem when using `exportAs` for directives!
*/
var resolvedPromise$1 = Promise.resolve(null);
/**
* \@whatItDoes Creates a {\@link FormControl} instance from a domain model and binds it
* to a form control element.
*
* The {\@link FormControl} instance will track the value, user interaction, and
* validation status of the control and keep the view synced with the model. If used
* within a parent form, the directive will also register itself with the form as a child
* control.
*
* \@howToUse
*
* This directive can be used by itself or as part of a larger form. All you need is the
* `ngModel` selector to activate it.
*
* It accepts a domain model as an optional {\@link Input}. If you have a one-way binding
* to `ngModel` with `[]` syntax, changing the value of the domain model in the component
* class will set the value in the view. If you have a two-way binding with `[()]` syntax
* (also known as 'banana-box syntax'), the value in the UI will always be synced back to
* the domain model in your class as well.
*
* If you wish to inspect the properties of the associated {\@link FormControl} (like
* validity state), you can also export the directive into a local template variable using
* `ngModel` as the key (ex: `#myVar="ngModel"`). You can then access the control using the
* directive's `control` property, but most properties you'll need (like `valid` and `dirty`)
* will fall through to the control anyway, so you can access them directly. You can see a
* full list of properties directly available in {\@link AbstractControlDirective}.
*
* The following is an example of a simple standalone control using `ngModel`:
*
* {\@example forms/ts/simpleNgModel/simple_ng_model_example.ts region='Component'}
*
* When using the `ngModel` within `<form>` tags, you'll also need to supply a `name` attribute
* so that the control can be registered with the parent form under that name.
*
* It's worth noting that in the context of a parent form, you often can skip one-way or
* two-way binding because the parent form will sync the value for you. You can access
* its properties by exporting it into a local template variable using `ngForm` (ex:
* `#f="ngForm"`). Then you can pass it where it needs to go on submit.
*
* If you do need to populate initial values into your form, using a one-way binding for
* `ngModel` tends to be sufficient as long as you use the exported form's value rather
* than the domain model's value on submit.
*
* Take a look at an example of using `ngModel` within a form:
*
* {\@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
*
* To see `ngModel` examples with different form control types, see:
*
* * Radio buttons: {\@link RadioControlValueAccessor}
* * Selects: {\@link SelectControlValueAccessor}
*
* **npm package**: `\@angular/forms`
*
* **NgModule**: `FormsModule`
*
* \@stable
*/
var NgModel = (function (_super) {
__extends(NgModel, _super);
/**
* @param {?} parent
* @param {?} validators
* @param {?} asyncValidators
* @param {?} valueAccessors
*/
function NgModel(parent, validators, asyncValidators, valueAccessors) {
var _this = _super.call(this) || this;
/**
* \@internal
*/
_this._control = new FormControl();
/**
* \@internal
*/
_this._registered = false;
_this.update = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["r" /* EventEmitter */]();
_this._parent = parent;
_this._rawValidators = validators || [];
_this._rawAsyncValidators = asyncValidators || [];
_this.valueAccessor = selectValueAccessor(_this, valueAccessors);
return _this;
}
/**
* @param {?} changes
* @return {?}
*/
NgModel.prototype.ngOnChanges = function (changes) {
this._checkForErrors();
if (!this._registered)
this._setUpControl();
if ('isDisabled' in changes) {
this._updateDisabled(changes);
}
if (isPropertyUpdated(changes, this.viewModel)) {
this._updateValue(this.model);
this.viewModel = this.model;
}
};
/**
* @return {?}
*/
NgModel.prototype.ngOnDestroy = function () { this.formDirective && this.formDirective.removeControl(this); };
Object.defineProperty(NgModel.prototype, "control", {
/**
* @return {?}
*/
get: function () { return this._control; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "path", {
/**
* @return {?}
*/
get: function () {
return this._parent ? controlPath(this.name, this._parent) : [this.name];
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "formDirective", {
/**
* @return {?}
*/
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "validator", {
/**
* @return {?}
*/
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "asyncValidator", {
/**
* @return {?}
*/
get: function () {
return composeAsyncValidators(this._rawAsyncValidators);
},
enumerable: true,
configurable: true
});
/**
* @param {?} newValue
* @return {?}
*/
NgModel.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
/**
* @return {?}
*/
NgModel.prototype._setUpControl = function () {
this._isStandalone() ? this._setUpStandalone() :
this.formDirective.addControl(this);
this._registered = true;
};
/**
* @return {?}
*/
NgModel.prototype._isStandalone = function () {
return !this._parent || !!(this.options && this.options.standalone);
};
/**
* @return {?}
*/
NgModel.prototype._setUpStandalone = function () {
setUpControl(this._control, this);
this._control.updateValueAndValidity({ emitEvent: false });
};
/**
* @return {?}
*/
NgModel.prototype._checkForErrors = function () {
if (!this._isStandalone()) {
this._checkParentType();
}
this._checkName();
};
/**
* @return {?}
*/
NgModel.prototype._checkParentType = function () {
if (!(this._parent instanceof NgModelGroup) &&
this._parent instanceof AbstractFormGroupDirective) {
TemplateDrivenErrors.formGroupNameException();
}
else if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) {
TemplateDrivenErrors.modelParentException();
}
};
/**
* @return {?}
*/
NgModel.prototype._checkName = function () {
if (this.options && this.options.name)
this.name = this.options.name;
if (!this._isStandalone() && !this.name) {
TemplateDrivenErrors.missingNameException();
}
};
/**
* @param {?} value
* @return {?}
*/
NgModel.prototype._updateValue = function (value) {
var _this = this;
resolvedPromise$1.then(function () { _this.control.setValue(value, { emitViewToModelChange: false }); });
};
/**
* @param {?} changes
* @return {?}
*/
NgModel.prototype._updateDisabled = function (changes) {
var _this = this;
var /** @type {?} */ disabledValue = changes['isDisabled'].currentValue;
var /** @type {?} */ isDisabled = disabledValue === '' || (disabledValue && disabledValue !== 'false');
resolvedPromise$1.then(function () {
if (isDisabled && !_this.control.disabled) {
_this.control.disable();
}
else if (!isDisabled && _this.control.disabled) {
_this.control.enable();
}
});
};
return NgModel;
}(NgControl));
NgModel.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: '[ngModel]:not([formControlName]):not([formControl])',
providers: [formControlBinding],
exportAs: 'ngModel'
},] },
];
/**
* @nocollapse
*/
NgModel.ctorParameters = function () { return [
{ type: ControlContainer, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_ASYNC_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALUE_ACCESSOR,] },] },
]; };
NgModel.propDecorators = {
'name': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'isDisabled': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['disabled',] },],
'model': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['ngModel',] },],
'options': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['ngModelOptions',] },],
'update': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["t" /* Output */], args: ['ngModelChange',] },],
};
/**
* @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
*/
var ReactiveErrors = (function () {
function ReactiveErrors() {
}
/**
* @return {?}
*/
ReactiveErrors.controlParentException = function () {
throw new Error("formControlName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + FormErrorExamples.formControlName);
};
/**
* @return {?}
*/
ReactiveErrors.ngModelGroupException = function () {
throw new Error("formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents\n that also have a \"form\" prefix: formGroupName, formArrayName, or formGroup.\n\n Option 1: Update the parent to be formGroupName (reactive form strategy)\n\n " + FormErrorExamples.formGroupName + "\n\n Option 2: Use ngModel instead of formControlName (template-driven strategy)\n\n " + FormErrorExamples.ngModelGroup);
};
/**
* @return {?}
*/
ReactiveErrors.missingFormException = function () {
throw new Error("formGroup expects a FormGroup instance. Please pass one in.\n\n Example:\n\n " + FormErrorExamples.formControlName);
};
/**
* @return {?}
*/
ReactiveErrors.groupParentException = function () {
throw new Error("formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + FormErrorExamples.formGroupName);
};
/**
* @return {?}
*/
ReactiveErrors.arrayParentException = function () {
throw new Error("formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + FormErrorExamples.formArrayName);
};
/**
* @return {?}
*/
ReactiveErrors.disabledAttrWarning = function () {
console.warn("\n It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true\n when you set up this control in your component class, the disabled attribute will actually be set in the DOM for\n you. We recommend using this approach to avoid 'changed after checked' errors.\n \n Example: \n form = new FormGroup({\n first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),\n last: new FormControl('Drew', Validators.required)\n });\n ");
};
return ReactiveErrors;
}());
/**
* @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
*/
var formControlBinding$1 = {
provide: NgControl,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return FormControlDirective; })
};
/**
* \@whatItDoes Syncs a standalone {\@link FormControl} instance to a form control element.
*
* In other words, this directive ensures that any values written to the {\@link FormControl}
* instance programmatically will be written to the DOM element (model -> view). Conversely,
* any values written to the DOM element through user input will be reflected in the
* {\@link FormControl} instance (view -> model).
*
* \@howToUse
*
* Use this directive if you'd like to create and manage a {\@link FormControl} instance directly.
* Simply create a {\@link FormControl}, save it to your component class, and pass it into the
* {\@link FormControlDirective}.
*
* This directive is designed to be used as a standalone control. Unlike {\@link FormControlName},
* it does not require that your {\@link FormControl} instance be part of any parent
* {\@link FormGroup}, and it won't be registered to any {\@link FormGroupDirective} that
* exists above it.
*
* **Get the value**: the `value` property is always synced and available on the
* {\@link FormControl} instance. See a full list of available properties in
* {\@link AbstractControl}.
*
* **Set the value**: You can pass in an initial value when instantiating the {\@link FormControl},
* or you can set it programmatically later using {\@link AbstractControl#setValue} or
* {\@link AbstractControl#patchValue}.
*
* **Listen to value**: If you want to listen to changes in the value of the control, you can
* subscribe to the {\@link AbstractControl#valueChanges} event. You can also listen to
* {\@link AbstractControl#statusChanges} to be notified when the validation status is
* re-calculated.
*
* ### Example
*
* {\@example forms/ts/simpleFormControl/simple_form_control_example.ts region='Component'}
*
* * **npm package**: `\@angular/forms`
*
* * **NgModule**: `ReactiveFormsModule`
*
* \@stable
*/
var FormControlDirective = (function (_super) {
__extends(FormControlDirective, _super);
/**
* @param {?} validators
* @param {?} asyncValidators
* @param {?} valueAccessors
*/
function FormControlDirective(validators, asyncValidators, valueAccessors) {
var _this = _super.call(this) || this;
_this.update = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["r" /* EventEmitter */]();
_this._rawValidators = validators || [];
_this._rawAsyncValidators = asyncValidators || [];
_this.valueAccessor = selectValueAccessor(_this, valueAccessors);
return _this;
}
Object.defineProperty(FormControlDirective.prototype, "isDisabled", {
/**
* @param {?} isDisabled
* @return {?}
*/
set: function (isDisabled) { ReactiveErrors.disabledAttrWarning(); },
enumerable: true,
configurable: true
});
/**
* @param {?} changes
* @return {?}
*/
FormControlDirective.prototype.ngOnChanges = function (changes) {
if (this._isControlChanged(changes)) {
setUpControl(this.form, this);
if (this.control.disabled && ((this.valueAccessor)).setDisabledState) {
((((this.valueAccessor)).setDisabledState))(true);
}
this.form.updateValueAndValidity({ emitEvent: false });
}
if (isPropertyUpdated(changes, this.viewModel)) {
this.form.setValue(this.model);
this.viewModel = this.model;
}
};
Object.defineProperty(FormControlDirective.prototype, "path", {
/**
* @return {?}
*/
get: function () { return []; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "validator", {
/**
* @return {?}
*/
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "asyncValidator", {
/**
* @return {?}
*/
get: function () {
return composeAsyncValidators(this._rawAsyncValidators);
},
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "control", {
/**
* @return {?}
*/
get: function () { return this.form; },
enumerable: true,
configurable: true
});
/**
* @param {?} newValue
* @return {?}
*/
FormControlDirective.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
/**
* @param {?} changes
* @return {?}
*/
FormControlDirective.prototype._isControlChanged = function (changes) {
return changes.hasOwnProperty('form');
};
return FormControlDirective;
}(NgControl));
FormControlDirective.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[formControl]', providers: [formControlBinding$1], exportAs: 'ngForm' },] },
];
/**
* @nocollapse
*/
FormControlDirective.ctorParameters = function () { return [
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_ASYNC_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALUE_ACCESSOR,] },] },
]; };
FormControlDirective.propDecorators = {
'form': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['formControl',] },],
'model': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['ngModel',] },],
'update': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["t" /* Output */], args: ['ngModelChange',] },],
'isDisabled': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['disabled',] },],
};
/**
* @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
*/
var formDirectiveProvider$1 = {
provide: ControlContainer,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return FormGroupDirective; })
};
/**
* \@whatItDoes Binds an existing {\@link FormGroup} to a DOM element.
*
* \@howToUse
*
* This directive accepts an existing {\@link FormGroup} instance. It will then use this
* {\@link FormGroup} instance to match any child {\@link FormControl}, {\@link FormGroup},
* and {\@link FormArray} instances to child {\@link FormControlName}, {\@link FormGroupName},
* and {\@link FormArrayName} directives.
*
* **Set value**: You can set the form's initial value when instantiating the
* {\@link FormGroup}, or you can set it programmatically later using the {\@link FormGroup}'s
* {\@link AbstractControl#setValue} or {\@link AbstractControl#patchValue} methods.
*
* **Listen to value**: If you want to listen to changes in the value of the form, you can subscribe
* to the {\@link FormGroup}'s {\@link AbstractControl#valueChanges} event. You can also listen to
* its {\@link AbstractControl#statusChanges} event to be notified when the validation status is
* re-calculated.
*
* Furthermore, you can listen to the directive's `ngSubmit` event to be notified when the user has
* triggered a form submission. The `ngSubmit` event will be emitted with the original form
* submission event.
*
* ### Example
*
* In this example, we create form controls for first name and last name.
*
* {\@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
*
* **npm package**: `\@angular/forms`
*
* **NgModule**: {\@link ReactiveFormsModule}
*
* \@stable
*/
var FormGroupDirective = (function (_super) {
__extends(FormGroupDirective, _super);
/**
* @param {?} _validators
* @param {?} _asyncValidators
*/
function FormGroupDirective(_validators, _asyncValidators) {
var _this = _super.call(this) || this;
_this._validators = _validators;
_this._asyncValidators = _asyncValidators;
_this._submitted = false;
_this.directives = [];
_this.form = ((null));
_this.ngSubmit = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["r" /* EventEmitter */]();
return _this;
}
/**
* @param {?} changes
* @return {?}
*/
FormGroupDirective.prototype.ngOnChanges = function (changes) {
this._checkFormPresent();
if (changes.hasOwnProperty('form')) {
this._updateValidators();
this._updateDomValue();
this._updateRegistrations();
}
};
Object.defineProperty(FormGroupDirective.prototype, "submitted", {
/**
* @return {?}
*/
get: function () { return this._submitted; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormGroupDirective.prototype, "formDirective", {
/**
* @return {?}
*/
get: function () { return this; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormGroupDirective.prototype, "control", {
/**
* @return {?}
*/
get: function () { return this.form; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormGroupDirective.prototype, "path", {
/**
* @return {?}
*/
get: function () { return []; },
enumerable: true,
configurable: true
});
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.addControl = function (dir) {
var /** @type {?} */ ctrl = this.form.get(dir.path);
setUpControl(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
this.directives.push(dir);
return ctrl;
};
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.getControl = function (dir) { return (this.form.get(dir.path)); };
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.removeControl = function (dir) { remove(this.directives, dir); };
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.addFormGroup = function (dir) {
var /** @type {?} */ ctrl = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
};
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.removeFormGroup = function (dir) { };
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.getFormGroup = function (dir) { return (this.form.get(dir.path)); };
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.addFormArray = function (dir) {
var /** @type {?} */ ctrl = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
};
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.removeFormArray = function (dir) { };
/**
* @param {?} dir
* @return {?}
*/
FormGroupDirective.prototype.getFormArray = function (dir) { return (this.form.get(dir.path)); };
/**
* @param {?} dir
* @param {?} value
* @return {?}
*/
FormGroupDirective.prototype.updateModel = function (dir, value) {
var /** @type {?} */ ctrl = (this.form.get(dir.path));
ctrl.setValue(value);
};
/**
* @param {?} $event
* @return {?}
*/
FormGroupDirective.prototype.onSubmit = function ($event) {
this._submitted = true;
this.ngSubmit.emit($event);
return false;
};
/**
* @return {?}
*/
FormGroupDirective.prototype.onReset = function () { this.resetForm(); };
/**
* @param {?=} value
* @return {?}
*/
FormGroupDirective.prototype.resetForm = function (value) {
if (value === void 0) { value = undefined; }
this.form.reset(value);
this._submitted = false;
};
/**
* \@internal
* @return {?}
*/
FormGroupDirective.prototype._updateDomValue = function () {
var _this = this;
this.directives.forEach(function (dir) {
var /** @type {?} */ newCtrl = _this.form.get(dir.path);
if (dir._control !== newCtrl) {
cleanUpControl(dir._control, dir);
if (newCtrl)
setUpControl(newCtrl, dir);
dir._control = newCtrl;
}
});
this.form._updateTreeValidity({ emitEvent: false });
};
/**
* @return {?}
*/
FormGroupDirective.prototype._updateRegistrations = function () {
var _this = this;
this.form._registerOnCollectionChange(function () { return _this._updateDomValue(); });
if (this._oldForm)
this._oldForm._registerOnCollectionChange(function () { });
this._oldForm = this.form;
};
/**
* @return {?}
*/
FormGroupDirective.prototype._updateValidators = function () {
var /** @type {?} */ sync = composeValidators(this._validators);
this.form.validator = Validators.compose([/** @type {?} */ ((this.form.validator)), /** @type {?} */ ((sync))]);
var /** @type {?} */ async = composeAsyncValidators(this._asyncValidators);
this.form.asyncValidator = Validators.composeAsync([/** @type {?} */ ((this.form.asyncValidator)), /** @type {?} */ ((async))]);
};
/**
* @return {?}
*/
FormGroupDirective.prototype._checkFormPresent = function () {
if (!this.form) {
ReactiveErrors.missingFormException();
}
};
return FormGroupDirective;
}(ControlContainer));
FormGroupDirective.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: '[formGroup]',
providers: [formDirectiveProvider$1],
host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' },
exportAs: 'ngForm'
},] },
];
/**
* @nocollapse
*/
FormGroupDirective.ctorParameters = function () { return [
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_ASYNC_VALIDATORS,] },] },
]; };
FormGroupDirective.propDecorators = {
'form': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['formGroup',] },],
'ngSubmit': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["t" /* Output */] },],
};
/**
* @template T
* @param {?} list
* @param {?} el
* @return {?}
*/
function remove(list, el) {
var /** @type {?} */ index = list.indexOf(el);
if (index > -1) {
list.splice(index, 1);
}
}
/**
* @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
*/
var formGroupNameProvider = {
provide: ControlContainer,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return FormGroupName; })
};
/**
* \@whatItDoes Syncs a nested {\@link FormGroup} to a DOM element.
*
* \@howToUse
*
* This directive can only be used with a parent {\@link FormGroupDirective} (selector:
* `[formGroup]`).
*
* It accepts the string name of the nested {\@link FormGroup} you want to link, and
* will look for a {\@link FormGroup} registered with that name in the parent
* {\@link FormGroup} instance you passed into {\@link FormGroupDirective}.
*
* Nested form groups can come in handy when you want to validate a sub-group of a
* form separately from the rest or when you'd like to group the values of certain
* controls into their own nested object.
*
* **Access the group**: You can access the associated {\@link FormGroup} using the
* {\@link AbstractControl#get} method. Ex: `this.form.get('name')`.
*
* You can also access individual controls within the group using dot syntax.
* Ex: `this.form.get('name.first')`
*
* **Get the value**: the `value` property is always synced and available on the
* {\@link FormGroup}. See a full list of available properties in {\@link AbstractControl}.
*
* **Set the value**: You can set an initial value for each child control when instantiating
* the {\@link FormGroup}, or you can set it programmatically later using
* {\@link AbstractControl#setValue} or {\@link AbstractControl#patchValue}.
*
* **Listen to value**: If you want to listen to changes in the value of the group, you can
* subscribe to the {\@link AbstractControl#valueChanges} event. You can also listen to
* {\@link AbstractControl#statusChanges} to be notified when the validation status is
* re-calculated.
*
* ### Example
*
* {\@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'}
*
* * **npm package**: `\@angular/forms`
*
* * **NgModule**: `ReactiveFormsModule`
*
* \@stable
*/
var FormGroupName = (function (_super) {
__extends(FormGroupName, _super);
/**
* @param {?} parent
* @param {?} validators
* @param {?} asyncValidators
*/
function FormGroupName(parent, validators, asyncValidators) {
var _this = _super.call(this) || this;
_this._parent = parent;
_this._validators = validators;
_this._asyncValidators = asyncValidators;
return _this;
}
/**
* \@internal
* @return {?}
*/
FormGroupName.prototype._checkParentType = function () {
if (_hasInvalidParent(this._parent)) {
ReactiveErrors.groupParentException();
}
};
return FormGroupName;
}(AbstractFormGroupDirective));
FormGroupName.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[formGroupName]', providers: [formGroupNameProvider] },] },
];
/**
* @nocollapse
*/
FormGroupName.ctorParameters = function () { return [
{ type: ControlContainer, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["s" /* SkipSelf */] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_ASYNC_VALIDATORS,] },] },
]; };
FormGroupName.propDecorators = {
'name': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['formGroupName',] },],
};
var formArrayNameProvider = {
provide: ControlContainer,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return FormArrayName; })
};
/**
* \@whatItDoes Syncs a nested {\@link FormArray} to a DOM element.
*
* \@howToUse
*
* This directive is designed to be used with a parent {\@link FormGroupDirective} (selector:
* `[formGroup]`).
*
* It accepts the string name of the nested {\@link FormArray} you want to link, and
* will look for a {\@link FormArray} registered with that name in the parent
* {\@link FormGroup} instance you passed into {\@link FormGroupDirective}.
*
* Nested form arrays can come in handy when you have a group of form controls but
* you're not sure how many there will be. Form arrays allow you to create new
* form controls dynamically.
*
* **Access the array**: You can access the associated {\@link FormArray} using the
* {\@link AbstractControl#get} method on the parent {\@link FormGroup}.
* Ex: `this.form.get('cities')`.
*
* **Get the value**: the `value` property is always synced and available on the
* {\@link FormArray}. See a full list of available properties in {\@link AbstractControl}.
*
* **Set the value**: You can set an initial value for each child control when instantiating
* the {\@link FormArray}, or you can set the value programmatically later using the
* {\@link FormArray}'s {\@link AbstractControl#setValue} or {\@link AbstractControl#patchValue}
* methods.
*
* **Listen to value**: If you want to listen to changes in the value of the array, you can
* subscribe to the {\@link FormArray}'s {\@link AbstractControl#valueChanges} event. You can also
* listen to its {\@link AbstractControl#statusChanges} event to be notified when the validation
* status is re-calculated.
*
* **Add new controls**: You can add new controls to the {\@link FormArray} dynamically by
* calling its {\@link FormArray.push} method.
* Ex: `this.form.get('cities').push(new FormControl());`
*
* ### Example
*
* {\@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'}
*
* * **npm package**: `\@angular/forms`
*
* * **NgModule**: `ReactiveFormsModule`
*
* \@stable
*/
var FormArrayName = (function (_super) {
__extends(FormArrayName, _super);
/**
* @param {?} parent
* @param {?} validators
* @param {?} asyncValidators
*/
function FormArrayName(parent, validators, asyncValidators) {
var _this = _super.call(this) || this;
_this._parent = parent;
_this._validators = validators;
_this._asyncValidators = asyncValidators;
return _this;
}
/**
* @return {?}
*/
FormArrayName.prototype.ngOnInit = function () {
this._checkParentType(); /** @type {?} */
((this.formDirective)).addFormArray(this);
};
/**
* @return {?}
*/
FormArrayName.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeFormArray(this);
}
};
Object.defineProperty(FormArrayName.prototype, "control", {
/**
* @return {?}
*/
get: function () { return ((this.formDirective)).getFormArray(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "formDirective", {
/**
* @return {?}
*/
get: function () {
return this._parent ? (this._parent.formDirective) : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "path", {
/**
* @return {?}
*/
get: function () { return controlPath(this.name, this._parent); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "validator", {
/**
* @return {?}
*/
get: function () { return composeValidators(this._validators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "asyncValidator", {
/**
* @return {?}
*/
get: function () {
return composeAsyncValidators(this._asyncValidators);
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
FormArrayName.prototype._checkParentType = function () {
if (_hasInvalidParent(this._parent)) {
ReactiveErrors.arrayParentException();
}
};
return FormArrayName;
}(ControlContainer));
FormArrayName.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[formArrayName]', providers: [formArrayNameProvider] },] },
];
/**
* @nocollapse
*/
FormArrayName.ctorParameters = function () { return [
{ type: ControlContainer, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["s" /* SkipSelf */] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_ASYNC_VALIDATORS,] },] },
]; };
FormArrayName.propDecorators = {
'name': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['formArrayName',] },],
};
/**
* @param {?} parent
* @return {?}
*/
function _hasInvalidParent(parent) {
return !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) &&
!(parent instanceof FormArrayName);
}
/**
* @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
*/
var controlNameBinding = {
provide: NgControl,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return FormControlName; })
};
/**
* \@whatItDoes Syncs a {\@link FormControl} in an existing {\@link FormGroup} to a form control
* element by name.
*
* In other words, this directive ensures that any values written to the {\@link FormControl}
* instance programmatically will be written to the DOM element (model -> view). Conversely,
* any values written to the DOM element through user input will be reflected in the
* {\@link FormControl} instance (view -> model).
*
* \@howToUse
*
* This directive is designed to be used with a parent {\@link FormGroupDirective} (selector:
* `[formGroup]`).
*
* It accepts the string name of the {\@link FormControl} instance you want to
* link, and will look for a {\@link FormControl} registered with that name in the
* closest {\@link FormGroup} or {\@link FormArray} above it.
*
* **Access the control**: You can access the {\@link FormControl} associated with
* this directive by using the {\@link AbstractControl#get} method.
* Ex: `this.form.get('first');`
*
* **Get value**: the `value` property is always synced and available on the {\@link FormControl}.
* See a full list of available properties in {\@link AbstractControl}.
*
* **Set value**: You can set an initial value for the control when instantiating the
* {\@link FormControl}, or you can set it programmatically later using
* {\@link AbstractControl#setValue} or {\@link AbstractControl#patchValue}.
*
* **Listen to value**: If you want to listen to changes in the value of the control, you can
* subscribe to the {\@link AbstractControl#valueChanges} event. You can also listen to
* {\@link AbstractControl#statusChanges} to be notified when the validation status is
* re-calculated.
*
* ### Example
*
* In this example, we create form controls for first name and last name.
*
* {\@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
*
* To see `formControlName` examples with different form control types, see:
*
* * Radio buttons: {\@link RadioControlValueAccessor}
* * Selects: {\@link SelectControlValueAccessor}
*
* **npm package**: `\@angular/forms`
*
* **NgModule**: {\@link ReactiveFormsModule}
*
* \@stable
*/
var FormControlName = (function (_super) {
__extends(FormControlName, _super);
/**
* @param {?} parent
* @param {?} validators
* @param {?} asyncValidators
* @param {?} valueAccessors
*/
function FormControlName(parent, validators, asyncValidators, valueAccessors) {
var _this = _super.call(this) || this;
_this._added = false;
_this.update = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["r" /* EventEmitter */]();
_this._parent = parent;
_this._rawValidators = validators || [];
_this._rawAsyncValidators = asyncValidators || [];
_this.valueAccessor = selectValueAccessor(_this, valueAccessors);
return _this;
}
Object.defineProperty(FormControlName.prototype, "isDisabled", {
/**
* @param {?} isDisabled
* @return {?}
*/
set: function (isDisabled) { ReactiveErrors.disabledAttrWarning(); },
enumerable: true,
configurable: true
});
/**
* @param {?} changes
* @return {?}
*/
FormControlName.prototype.ngOnChanges = function (changes) {
if (!this._added)
this._setUpControl();
if (isPropertyUpdated(changes, this.viewModel)) {
this.viewModel = this.model;
this.formDirective.updateModel(this, this.model);
}
};
/**
* @return {?}
*/
FormControlName.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeControl(this);
}
};
/**
* @param {?} newValue
* @return {?}
*/
FormControlName.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
Object.defineProperty(FormControlName.prototype, "path", {
/**
* @return {?}
*/
get: function () { return controlPath(this.name, /** @type {?} */ ((this._parent))); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "formDirective", {
/**
* @return {?}
*/
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "validator", {
/**
* @return {?}
*/
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "asyncValidator", {
/**
* @return {?}
*/
get: function () {
return ((composeAsyncValidators(this._rawAsyncValidators)));
},
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "control", {
/**
* @return {?}
*/
get: function () { return this._control; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
FormControlName.prototype._checkParentType = function () {
if (!(this._parent instanceof FormGroupName) &&
this._parent instanceof AbstractFormGroupDirective) {
ReactiveErrors.ngModelGroupException();
}
else if (!(this._parent instanceof FormGroupName) && !(this._parent instanceof FormGroupDirective) &&
!(this._parent instanceof FormArrayName)) {
ReactiveErrors.controlParentException();
}
};
/**
* @return {?}
*/
FormControlName.prototype._setUpControl = function () {
this._checkParentType();
this._control = this.formDirective.addControl(this);
if (this.control.disabled && ((this.valueAccessor)).setDisabledState) {
((((this.valueAccessor)).setDisabledState))(true);
}
this._added = true;
};
return FormControlName;
}(NgControl));
FormControlName.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[formControlName]', providers: [controlNameBinding] },] },
];
/**
* @nocollapse
*/
FormControlName.ctorParameters = function () { return [
{ type: ControlContainer, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["s" /* SkipSelf */] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_ASYNC_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [NG_VALUE_ACCESSOR,] },] },
]; };
FormControlName.propDecorators = {
'name': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['formControlName',] },],
'model': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['ngModel',] },],
'update': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["t" /* Output */], args: ['ngModelChange',] },],
'isDisabled': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['disabled',] },],
};
/**
* @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
*/
var REQUIRED_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return RequiredValidator; }),
multi: true
};
var CHECKBOX_REQUIRED_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return CheckboxRequiredValidator; }),
multi: true
};
/**
* A Directive that adds the `required` validator to any controls marked with the
* `required` attribute, via the {\@link NG_VALIDATORS} binding.
*
* ### Example
*
* ```
* <input name="fullName" ngModel required>
* ```
*
* \@stable
*/
var RequiredValidator = (function () {
function RequiredValidator() {
}
Object.defineProperty(RequiredValidator.prototype, "required", {
/**
* @return {?}
*/
get: function () { return this._required; },
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
this._required = value != null && value !== false && "" + value !== 'false';
if (this._onChange)
this._onChange();
},
enumerable: true,
configurable: true
});
/**
* @param {?} c
* @return {?}
*/
RequiredValidator.prototype.validate = function (c) {
return this.required ? Validators.required(c) : null;
};
/**
* @param {?} fn
* @return {?}
*/
RequiredValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
return RequiredValidator;
}());
RequiredValidator.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]',
providers: [REQUIRED_VALIDATOR],
host: { '[attr.required]': 'required ? "" : null' }
},] },
];
/**
* @nocollapse
*/
RequiredValidator.ctorParameters = function () { return []; };
RequiredValidator.propDecorators = {
'required': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* A Directive that adds the `required` validator to checkbox controls marked with the
* `required` attribute, via the {\@link NG_VALIDATORS} binding.
*
* ### Example
*
* ```
* <input type="checkbox" name="active" ngModel required>
* ```
*
* \@experimental
*/
var CheckboxRequiredValidator = (function (_super) {
__extends(CheckboxRequiredValidator, _super);
function CheckboxRequiredValidator() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} c
* @return {?}
*/
CheckboxRequiredValidator.prototype.validate = function (c) {
return this.required ? Validators.requiredTrue(c) : null;
};
return CheckboxRequiredValidator;
}(RequiredValidator));
CheckboxRequiredValidator.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'input[type=checkbox][required][formControlName],input[type=checkbox][required][formControl],input[type=checkbox][required][ngModel]',
providers: [CHECKBOX_REQUIRED_VALIDATOR],
host: { '[attr.required]': 'required ? "" : null' }
},] },
];
/**
* @nocollapse
*/
CheckboxRequiredValidator.ctorParameters = function () { return []; };
/**
* Provider which adds {@link EmailValidator} to {@link NG_VALIDATORS}.
*/
var EMAIL_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return EmailValidator; }),
multi: true
};
/**
* A Directive that adds the `email` validator to controls marked with the
* `email` attribute, via the {\@link NG_VALIDATORS} binding.
*
* ### Example
*
* ```
* <input type="email" name="email" ngModel email>
* <input type="email" name="email" ngModel email="true">
* <input type="email" name="email" ngModel [email]="true">
* ```
*
* \@experimental
*/
var EmailValidator = (function () {
function EmailValidator() {
}
Object.defineProperty(EmailValidator.prototype, "email", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
this._enabled = value === '' || value === true || value === 'true';
if (this._onChange)
this._onChange();
},
enumerable: true,
configurable: true
});
/**
* @param {?} c
* @return {?}
*/
EmailValidator.prototype.validate = function (c) {
return this._enabled ? Validators.email(c) : null;
};
/**
* @param {?} fn
* @return {?}
*/
EmailValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
return EmailValidator;
}());
EmailValidator.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: '[email][formControlName],[email][formControl],[email][ngModel]',
providers: [EMAIL_VALIDATOR]
},] },
];
/**
* @nocollapse
*/
EmailValidator.ctorParameters = function () { return []; };
EmailValidator.propDecorators = {
'email': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* Provider which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}.
*
* ## Example:
*
* {@example common/forms/ts/validators/validators.ts region='min'}
*/
var MIN_LENGTH_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return MinLengthValidator; }),
multi: true
};
/**
* A directive which installs the {\@link MinLengthValidator} for any `formControlName`,
* `formControl`, or control with `ngModel` that also has a `minlength` attribute.
*
* \@stable
*/
var MinLengthValidator = (function () {
function MinLengthValidator() {
}
/**
* @param {?} changes
* @return {?}
*/
MinLengthValidator.prototype.ngOnChanges = function (changes) {
if ('minlength' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
/**
* @param {?} c
* @return {?}
*/
MinLengthValidator.prototype.validate = function (c) {
return this.minlength == null ? null : this._validator(c);
};
/**
* @param {?} fn
* @return {?}
*/
MinLengthValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
/**
* @return {?}
*/
MinLengthValidator.prototype._createValidator = function () {
this._validator = Validators.minLength(parseInt(this.minlength, 10));
};
return MinLengthValidator;
}());
MinLengthValidator.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]',
providers: [MIN_LENGTH_VALIDATOR],
host: { '[attr.minlength]': 'minlength ? minlength : null' }
},] },
];
/**
* @nocollapse
*/
MinLengthValidator.ctorParameters = function () { return []; };
MinLengthValidator.propDecorators = {
'minlength': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* Provider which adds {@link MaxLengthValidator} to {@link NG_VALIDATORS}.
*
* ## Example:
*
* {@example common/forms/ts/validators/validators.ts region='max'}
*/
var MAX_LENGTH_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return MaxLengthValidator; }),
multi: true
};
/**
* A directive which installs the {\@link MaxLengthValidator} for any `formControlName,
* `formControl`,
* or control with `ngModel` that also has a `maxlength` attribute.
*
* \@stable
*/
var MaxLengthValidator = (function () {
function MaxLengthValidator() {
}
/**
* @param {?} changes
* @return {?}
*/
MaxLengthValidator.prototype.ngOnChanges = function (changes) {
if ('maxlength' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
/**
* @param {?} c
* @return {?}
*/
MaxLengthValidator.prototype.validate = function (c) {
return this.maxlength != null ? this._validator(c) : null;
};
/**
* @param {?} fn
* @return {?}
*/
MaxLengthValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
/**
* @return {?}
*/
MaxLengthValidator.prototype._createValidator = function () {
this._validator = Validators.maxLength(parseInt(this.maxlength, 10));
};
return MaxLengthValidator;
}());
MaxLengthValidator.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]',
providers: [MAX_LENGTH_VALIDATOR],
host: { '[attr.maxlength]': 'maxlength ? maxlength : null' }
},] },
];
/**
* @nocollapse
*/
MaxLengthValidator.ctorParameters = function () { return []; };
MaxLengthValidator.propDecorators = {
'maxlength': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
var PATTERN_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["d" /* forwardRef */])(function () { return PatternValidator; }),
multi: true
};
/**
* A Directive that adds the `pattern` validator to any controls marked with the
* `pattern` attribute, via the {\@link NG_VALIDATORS} binding. Uses attribute value
* as the regex to validate Control value against. Follows pattern attribute
* semantics; i.e. regex must match entire Control value.
*
* ### Example
*
* ```
* <input [name]="fullName" pattern="[a-zA-Z ]*" ngModel>
* ```
* \@stable
*/
var PatternValidator = (function () {
function PatternValidator() {
}
/**
* @param {?} changes
* @return {?}
*/
PatternValidator.prototype.ngOnChanges = function (changes) {
if ('pattern' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
/**
* @param {?} c
* @return {?}
*/
PatternValidator.prototype.validate = function (c) { return this._validator(c); };
/**
* @param {?} fn
* @return {?}
*/
PatternValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
/**
* @return {?}
*/
PatternValidator.prototype._createValidator = function () { this._validator = Validators.pattern(this.pattern); };
return PatternValidator;
}());
PatternValidator.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]',
providers: [PATTERN_VALIDATOR],
host: { '[attr.pattern]': 'pattern ? pattern : null' }
},] },
];
/**
* @nocollapse
*/
PatternValidator.ctorParameters = function () { return []; };
PatternValidator.propDecorators = {
'pattern': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* @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
*/
/**
* \@whatItDoes Creates an {\@link AbstractControl} from a user-specified configuration.
*
* It is essentially syntactic sugar that shortens the `new FormGroup()`,
* `new FormControl()`, and `new FormArray()` boilerplate that can build up in larger
* forms.
*
* \@howToUse
*
* To use, inject `FormBuilder` into your component class. You can then call its methods
* directly.
*
* {\@example forms/ts/formBuilder/form_builder_example.ts region='Component'}
*
* * **npm package**: `\@angular/forms`
*
* * **NgModule**: {\@link ReactiveFormsModule}
*
* \@stable
*/
var FormBuilder = (function () {
function FormBuilder() {
}
/**
* Construct a new {\@link FormGroup} with the given map of configuration.
* Valid keys for the `extra` parameter map are `validator` and `asyncValidator`.
*
* See the {\@link FormGroup} constructor for more details.
* @param {?} controlsConfig
* @param {?=} extra
* @return {?}
*/
FormBuilder.prototype.group = function (controlsConfig, extra) {
if (extra === void 0) { extra = null; }
var /** @type {?} */ controls = this._reduceControls(controlsConfig);
var /** @type {?} */ validator = extra != null ? extra['validator'] : null;
var /** @type {?} */ asyncValidator = extra != null ? extra['asyncValidator'] : null;
return new FormGroup(controls, validator, asyncValidator);
};
/**
* Construct a new {\@link FormControl} with the given `formState`,`validator`, and
* `asyncValidator`.
*
* `formState` can either be a standalone value for the form control or an object
* that contains both a value and a disabled status.
*
* @param {?} formState
* @param {?=} validator
* @param {?=} asyncValidator
* @return {?}
*/
FormBuilder.prototype.control = function (formState, validator, asyncValidator) {
return new FormControl(formState, validator, asyncValidator);
};
/**
* Construct a {\@link FormArray} from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`.
* @param {?} controlsConfig
* @param {?=} validator
* @param {?=} asyncValidator
* @return {?}
*/
FormBuilder.prototype.array = function (controlsConfig, validator, asyncValidator) {
var _this = this;
var /** @type {?} */ controls = controlsConfig.map(function (c) { return _this._createControl(c); });
return new FormArray(controls, validator, asyncValidator);
};
/**
* \@internal
* @param {?} controlsConfig
* @return {?}
*/
FormBuilder.prototype._reduceControls = function (controlsConfig) {
var _this = this;
var /** @type {?} */ controls = {};
Object.keys(controlsConfig).forEach(function (controlName) {
controls[controlName] = _this._createControl(controlsConfig[controlName]);
});
return controls;
};
/**
* \@internal
* @param {?} controlConfig
* @return {?}
*/
FormBuilder.prototype._createControl = function (controlConfig) {
if (controlConfig instanceof FormControl || controlConfig instanceof FormGroup ||
controlConfig instanceof FormArray) {
return controlConfig;
}
else if (Array.isArray(controlConfig)) {
var /** @type {?} */ value = controlConfig[0];
var /** @type {?} */ validator = controlConfig.length > 1 ? controlConfig[1] : null;
var /** @type {?} */ asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
}
else {
return this.control(controlConfig);
}
};
return FormBuilder;
}());
FormBuilder.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
FormBuilder.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
var VERSION = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["u" /* Version */]('4.1.1');
/**
* @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
*/
/**
* \@whatItDoes Adds `novalidate` attribute to all forms by default.
*
* `novalidate` is used to disable browser's native form validation.
*
* If you want to use native validation with Angular forms, just add `ngNativeValidate` attribute:
*
* ```
* <form ngNativeValidate></form>
* ```
*
* \@experimental
*/
var NgNoValidate = (function () {
function NgNoValidate() {
}
return NgNoValidate;
}());
NgNoValidate.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{
selector: 'form:not([ngNoForm]):not([ngNativeValidate])',
host: { 'novalidate': '' },
},] },
];
/**
* @nocollapse
*/
NgNoValidate.ctorParameters = function () { return []; };
/**
* @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
*/
var SHARED_FORM_DIRECTIVES = [
NgNoValidate,
NgSelectOption,
NgSelectMultipleOption,
DefaultValueAccessor,
NumberValueAccessor,
RangeValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
NgControlStatus,
NgControlStatusGroup,
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator,
CheckboxRequiredValidator,
EmailValidator,
];
var TEMPLATE_DRIVEN_DIRECTIVES = [NgModel, NgModelGroup, NgForm];
var REACTIVE_DRIVEN_DIRECTIVES = [FormControlDirective, FormGroupDirective, FormControlName, FormGroupName, FormArrayName];
/**
* Internal module used for sharing directives between FormsModule and ReactiveFormsModule
*/
var InternalFormsSharedModule = (function () {
function InternalFormsSharedModule() {
}
return InternalFormsSharedModule;
}());
InternalFormsSharedModule.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */], args: [{
declarations: SHARED_FORM_DIRECTIVES,
exports: SHARED_FORM_DIRECTIVES,
},] },
];
/**
* @nocollapse
*/
InternalFormsSharedModule.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* The ng module for forms.
* \@stable
*/
var FormsModule = (function () {
function FormsModule() {
}
return FormsModule;
}());
FormsModule.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */], args: [{
declarations: TEMPLATE_DRIVEN_DIRECTIVES,
providers: [RadioControlRegistry],
exports: [InternalFormsSharedModule, TEMPLATE_DRIVEN_DIRECTIVES]
},] },
];
/**
* @nocollapse
*/
FormsModule.ctorParameters = function () { return []; };
/**
* The ng module for reactive forms.
* \@stable
*/
var ReactiveFormsModule = (function () {
function ReactiveFormsModule() {
}
return ReactiveFormsModule;
}());
ReactiveFormsModule.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */], args: [{
declarations: [REACTIVE_DRIVEN_DIRECTIVES],
providers: [FormBuilder, RadioControlRegistry],
exports: [InternalFormsSharedModule, REACTIVE_DRIVEN_DIRECTIVES]
},] },
];
/**
* @nocollapse
*/
ReactiveFormsModule.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* @module
* @description
* This module is used for handling user input, by defining and building a {@link FormGroup} that
* consists of {@link FormControl} objects, and mapping them onto the DOM. {@link FormControl}
* objects can then be used to read information from the form DOM elements.
*
* Forms providers are not included in default providers; you must import these providers
* explicitly.
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the forms package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=forms.es5.js.map
/***/ }),
/* 10 */,
/* 11 */,
/* 12 */,
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_rxjs_Observable__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_rxjs_Observable___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_rxjs_Observable__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_platform_browser__ = __webpack_require__(22);
/* unused harmony export BrowserXhr */
/* unused harmony export JSONPBackend */
/* unused harmony export JSONPConnection */
/* unused harmony export CookieXSRFStrategy */
/* unused harmony export XHRBackend */
/* unused harmony export XHRConnection */
/* unused harmony export BaseRequestOptions */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return RequestOptions; });
/* unused harmony export BaseResponseOptions */
/* unused harmony export ResponseOptions */
/* unused harmony export ReadyState */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return RequestMethod; });
/* unused harmony export ResponseContentType */
/* unused harmony export ResponseType */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Headers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return Http; });
/* unused harmony export Jsonp */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HttpModule; });
/* unused harmony export JsonpModule */
/* unused harmony export Connection */
/* unused harmony export ConnectionBackend */
/* unused harmony export XSRFStrategy */
/* unused harmony export Request */
/* unused harmony export Response */
/* unused harmony export QueryEncoder */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return URLSearchParams; });
/* unused harmony export VERSION */
/* unused harmony export ɵg */
/* unused harmony export ɵa */
/* unused harmony export ɵf */
/* unused harmony export ɵb */
/* unused harmony export ɵc */
/* unused harmony export ɵd */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.1
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @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
*/
/**
* A backend for http that uses the `XMLHttpRequest` browser API.
*
* Take care not to evaluate this in non-browser contexts.
*
* \@experimental
*/
var BrowserXhr = (function () {
function BrowserXhr() {
}
/**
* @return {?}
*/
BrowserXhr.prototype.build = function () { return ((new XMLHttpRequest())); };
return BrowserXhr;
}());
BrowserXhr.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
BrowserXhr.ctorParameters = function () { return []; };
var RequestMethod = {};
RequestMethod.Get = 0;
RequestMethod.Post = 1;
RequestMethod.Put = 2;
RequestMethod.Delete = 3;
RequestMethod.Options = 4;
RequestMethod.Head = 5;
RequestMethod.Patch = 6;
RequestMethod[RequestMethod.Get] = "Get";
RequestMethod[RequestMethod.Post] = "Post";
RequestMethod[RequestMethod.Put] = "Put";
RequestMethod[RequestMethod.Delete] = "Delete";
RequestMethod[RequestMethod.Options] = "Options";
RequestMethod[RequestMethod.Head] = "Head";
RequestMethod[RequestMethod.Patch] = "Patch";
var ReadyState = {};
ReadyState.Unsent = 0;
ReadyState.Open = 1;
ReadyState.HeadersReceived = 2;
ReadyState.Loading = 3;
ReadyState.Done = 4;
ReadyState.Cancelled = 5;
ReadyState[ReadyState.Unsent] = "Unsent";
ReadyState[ReadyState.Open] = "Open";
ReadyState[ReadyState.HeadersReceived] = "HeadersReceived";
ReadyState[ReadyState.Loading] = "Loading";
ReadyState[ReadyState.Done] = "Done";
ReadyState[ReadyState.Cancelled] = "Cancelled";
var ResponseType = {};
ResponseType.Basic = 0;
ResponseType.Cors = 1;
ResponseType.Default = 2;
ResponseType.Error = 3;
ResponseType.Opaque = 4;
ResponseType[ResponseType.Basic] = "Basic";
ResponseType[ResponseType.Cors] = "Cors";
ResponseType[ResponseType.Default] = "Default";
ResponseType[ResponseType.Error] = "Error";
ResponseType[ResponseType.Opaque] = "Opaque";
var ContentType = {};
ContentType.NONE = 0;
ContentType.JSON = 1;
ContentType.FORM = 2;
ContentType.FORM_DATA = 3;
ContentType.TEXT = 4;
ContentType.BLOB = 5;
ContentType.ARRAY_BUFFER = 6;
ContentType[ContentType.NONE] = "NONE";
ContentType[ContentType.JSON] = "JSON";
ContentType[ContentType.FORM] = "FORM";
ContentType[ContentType.FORM_DATA] = "FORM_DATA";
ContentType[ContentType.TEXT] = "TEXT";
ContentType[ContentType.BLOB] = "BLOB";
ContentType[ContentType.ARRAY_BUFFER] = "ARRAY_BUFFER";
var ResponseContentType = {};
ResponseContentType.Text = 0;
ResponseContentType.Json = 1;
ResponseContentType.ArrayBuffer = 2;
ResponseContentType.Blob = 3;
ResponseContentType[ResponseContentType.Text] = "Text";
ResponseContentType[ResponseContentType.Json] = "Json";
ResponseContentType[ResponseContentType.ArrayBuffer] = "ArrayBuffer";
ResponseContentType[ResponseContentType.Blob] = "Blob";
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers), as
* specified in the [Fetch Spec](https://fetch.spec.whatwg.org/#headers-class).
*
* The only known difference between this `Headers` implementation and the spec is the
* lack of an `entries` method.
*
* ### Example
*
* ```
* import {Headers} from '\@angular/http';
*
* var firstHeaders = new Headers();
* firstHeaders.append('Content-Type', 'image/jpeg');
* console.log(firstHeaders.get('Content-Type')) //'image/jpeg'
*
* // Create headers from Plain Old JavaScript Object
* var secondHeaders = new Headers({
* 'X-My-Custom-Header': 'Angular'
* });
* console.log(secondHeaders.get('X-My-Custom-Header')); //'Angular'
*
* var thirdHeaders = new Headers(secondHeaders);
* console.log(thirdHeaders.get('X-My-Custom-Header')); //'Angular'
* ```
*
* \@experimental
*/
var Headers = (function () {
/**
* @param {?=} headers
*/
function Headers(headers) {
var _this = this;
/**
* \@internal header names are lower case
*/
this._headers = new Map();
/**
* \@internal map lower case names to actual names
*/
this._normalizedNames = new Map();
if (!headers) {
return;
}
if (headers instanceof Headers) {
headers.forEach(function (values, name) {
values.forEach(function (value) { return _this.append(name, value); });
});
return;
}
Object.keys(headers).forEach(function (name) {
var values = Array.isArray(headers[name]) ? headers[name] : [headers[name]];
_this.delete(name);
values.forEach(function (value) { return _this.append(name, value); });
});
}
/**
* Returns a new Headers instance from the given DOMString of Response Headers
* @param {?} headersString
* @return {?}
*/
Headers.fromResponseHeaderString = function (headersString) {
var /** @type {?} */ headers = new Headers();
headersString.split('\n').forEach(function (line) {
var /** @type {?} */ index = line.indexOf(':');
if (index > 0) {
var /** @type {?} */ name = line.slice(0, index);
var /** @type {?} */ value = line.slice(index + 1).trim();
headers.set(name, value);
}
});
return headers;
};
/**
* Appends a header to existing list of header values for a given header name.
* @param {?} name
* @param {?} value
* @return {?}
*/
Headers.prototype.append = function (name, value) {
var /** @type {?} */ values = this.getAll(name);
if (values === null) {
this.set(name, value);
}
else {
values.push(value);
}
};
/**
* Deletes all header values for the given name.
* @param {?} name
* @return {?}
*/
Headers.prototype.delete = function (name) {
var /** @type {?} */ lcName = name.toLowerCase();
this._normalizedNames.delete(lcName);
this._headers.delete(lcName);
};
/**
* @param {?} fn
* @return {?}
*/
Headers.prototype.forEach = function (fn) {
var _this = this;
this._headers.forEach(function (values, lcName) { return fn(values, _this._normalizedNames.get(lcName), _this._headers); });
};
/**
* Returns first header that matches given name.
* @param {?} name
* @return {?}
*/
Headers.prototype.get = function (name) {
var /** @type {?} */ values = this.getAll(name);
if (values === null) {
return null;
}
return values.length > 0 ? values[0] : null;
};
/**
* Checks for existence of header by given name.
* @param {?} name
* @return {?}
*/
Headers.prototype.has = function (name) { return this._headers.has(name.toLowerCase()); };
/**
* Returns the names of the headers
* @return {?}
*/
Headers.prototype.keys = function () { return Array.from(this._normalizedNames.values()); };
/**
* Sets or overrides header value for given name.
* @param {?} name
* @param {?} value
* @return {?}
*/
Headers.prototype.set = function (name, value) {
if (Array.isArray(value)) {
if (value.length) {
this._headers.set(name.toLowerCase(), [value.join(',')]);
}
}
else {
this._headers.set(name.toLowerCase(), [value]);
}
this.mayBeSetNormalizedName(name);
};
/**
* Returns values of all headers.
* @return {?}
*/
Headers.prototype.values = function () { return Array.from(this._headers.values()); };
/**
* @return {?}
*/
Headers.prototype.toJSON = function () {
var _this = this;
var /** @type {?} */ serialized = {};
this._headers.forEach(function (values, name) {
var /** @type {?} */ split = [];
values.forEach(function (v) { return split.push.apply(split, v.split(',')); });
serialized[((_this._normalizedNames.get(name)))] = split;
});
return serialized;
};
/**
* Returns list of header values for a given name.
* @param {?} name
* @return {?}
*/
Headers.prototype.getAll = function (name) {
return this.has(name) ? this._headers.get(name.toLowerCase()) || null : null;
};
/**
* This method is not implemented.
* @return {?}
*/
Headers.prototype.entries = function () { throw new Error('"entries" method is not implemented on Headers class'); };
/**
* @param {?} name
* @return {?}
*/
Headers.prototype.mayBeSetNormalizedName = function (name) {
var /** @type {?} */ lcName = name.toLowerCase();
if (!this._normalizedNames.has(lcName)) {
this._normalizedNames.set(lcName, name);
}
};
return Headers;
}());
/**
* @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
*/
/**
* Creates a response options object to be optionally provided when instantiating a
* {\@link Response}.
*
* This class is based on the `ResponseInit` description in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#responseinit).
*
* All values are null by default. Typical defaults can be found in the
* {\@link BaseResponseOptions} class, which sub-classes `ResponseOptions`.
*
* This class may be used in tests to build {\@link Response Responses} for
* mock responses (see {\@link MockBackend}).
*
* ### Example ([live demo](http://plnkr.co/edit/P9Jkk8e8cz6NVzbcxEsD?p=preview))
*
* ```typescript
* import {ResponseOptions, Response} from '\@angular/http';
*
* var options = new ResponseOptions({
* body: '{"name":"Jeff"}'
* });
* var res = new Response(options);
*
* console.log('res.json():', res.json()); // Object {name: "Jeff"}
* ```
*
* \@experimental
*/
var ResponseOptions = (function () {
/**
* @param {?=} __0
*/
function ResponseOptions(_a) {
var _b = _a === void 0 ? {} : _a, body = _b.body, status = _b.status, headers = _b.headers, statusText = _b.statusText, type = _b.type, url = _b.url;
this.body = body != null ? body : null;
this.status = status != null ? status : null;
this.headers = headers != null ? headers : null;
this.statusText = statusText != null ? statusText : null;
this.type = type != null ? type : null;
this.url = url != null ? url : null;
}
/**
* Creates a copy of the `ResponseOptions` instance, using the optional input as values to
* override
* existing values. This method will not change the values of the instance on which it is being
* called.
*
* This may be useful when sharing a base `ResponseOptions` object inside tests,
* where certain properties may change from test to test.
*
* ### Example ([live demo](http://plnkr.co/edit/1lXquqFfgduTFBWjNoRE?p=preview))
*
* ```typescript
* import {ResponseOptions, Response} from '\@angular/http';
*
* var options = new ResponseOptions({
* body: {name: 'Jeff'}
* });
* var res = new Response(options.merge({
* url: 'https://google.com'
* }));
* console.log('options.url:', options.url); // null
* console.log('res.json():', res.json()); // Object {name: "Jeff"}
* console.log('res.url:', res.url); // https://google.com
* ```
* @param {?=} options
* @return {?}
*/
ResponseOptions.prototype.merge = function (options) {
return new ResponseOptions({
body: options && options.body != null ? options.body : this.body,
status: options && options.status != null ? options.status : this.status,
headers: options && options.headers != null ? options.headers : this.headers,
statusText: options && options.statusText != null ? options.statusText : this.statusText,
type: options && options.type != null ? options.type : this.type,
url: options && options.url != null ? options.url : this.url,
});
};
return ResponseOptions;
}());
/**
* Subclass of {\@link ResponseOptions}, with default values.
*
* Default values:
* * status: 200
* * headers: empty {\@link Headers} object
*
* This class could be extended and bound to the {\@link ResponseOptions} class
* when configuring an {\@link Injector}, in order to override the default options
* used by {\@link Http} to create {\@link Response Responses}.
*
* ### Example ([live demo](http://plnkr.co/edit/qv8DLT?p=preview))
*
* ```typescript
* import {provide} from '\@angular/core';
* import {bootstrap} from '\@angular/platform-browser/browser';
* import {HTTP_PROVIDERS, Headers, Http, BaseResponseOptions, ResponseOptions} from
* '\@angular/http';
* import {App} from './myapp';
*
* class MyOptions extends BaseResponseOptions {
* headers:Headers = new Headers({network: 'github'});
* }
*
* bootstrap(App, [HTTP_PROVIDERS, {provide: ResponseOptions, useClass: MyOptions}]);
* ```
*
* The options could also be extended when manually creating a {\@link Response}
* object.
*
* ### Example ([live demo](http://plnkr.co/edit/VngosOWiaExEtbstDoix?p=preview))
*
* ```
* import {BaseResponseOptions, Response} from '\@angular/http';
*
* var options = new BaseResponseOptions();
* var res = new Response(options.merge({
* body: 'Angular',
* headers: new Headers({framework: 'angular'})
* }));
* console.log('res.headers.get("framework"):', res.headers.get('framework')); // angular
* console.log('res.text():', res.text()); // Angular;
* ```
*
* \@experimental
*/
var BaseResponseOptions = (function (_super) {
__extends(BaseResponseOptions, _super);
function BaseResponseOptions() {
return _super.call(this, { status: 200, statusText: 'Ok', type: ResponseType.Default, headers: new Headers() }) || this;
}
return BaseResponseOptions;
}(ResponseOptions));
BaseResponseOptions.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
BaseResponseOptions.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* Abstract class from which real backends are derived.
*
* The primary purpose of a `ConnectionBackend` is to create new connections to fulfill a given
* {\@link Request}.
*
* \@experimental
* @abstract
*/
var ConnectionBackend = (function () {
function ConnectionBackend() {
}
/**
* @abstract
* @param {?} request
* @return {?}
*/
ConnectionBackend.prototype.createConnection = function (request) { };
return ConnectionBackend;
}());
/**
* Abstract class from which real connections are derived.
*
* \@experimental
* @abstract
*/
var Connection = (function () {
function Connection() {
}
return Connection;
}());
/**
* An XSRFStrategy configures XSRF protection (e.g. via headers) on an HTTP request.
*
* \@experimental
* @abstract
*/
var XSRFStrategy = (function () {
function XSRFStrategy() {
}
/**
* @abstract
* @param {?} req
* @return {?}
*/
XSRFStrategy.prototype.configureRequest = function (req) { };
return XSRFStrategy;
}());
/**
* @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
*/
/**
* @param {?} method
* @return {?}
*/
function normalizeMethodName(method) {
if (typeof method !== 'string')
return method;
switch (method.toUpperCase()) {
case 'GET':
return RequestMethod.Get;
case 'POST':
return RequestMethod.Post;
case 'PUT':
return RequestMethod.Put;
case 'DELETE':
return RequestMethod.Delete;
case 'OPTIONS':
return RequestMethod.Options;
case 'HEAD':
return RequestMethod.Head;
case 'PATCH':
return RequestMethod.Patch;
}
throw new Error("Invalid request method. The method \"" + method + "\" is not supported.");
}
var isSuccess = function (status) { return (status >= 200 && status < 300); };
/**
* @param {?} xhr
* @return {?}
*/
function getResponseURL(xhr) {
if ('responseURL' in xhr) {
return xhr.responseURL;
}
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL');
}
return null;
}
/**
* @param {?} input
* @return {?}
*/
function stringToArrayBuffer(input) {
var /** @type {?} */ view = new Uint16Array(input.length);
for (var /** @type {?} */ i = 0, /** @type {?} */ strLen = input.length; i < strLen; i++) {
view[i] = input.charCodeAt(i);
}
return view.buffer;
}
/**
* @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
* @param {?=} rawParams
* @return {?}
*/
function paramParser(rawParams) {
if (rawParams === void 0) { rawParams = ''; }
var /** @type {?} */ map = new Map();
if (rawParams.length > 0) {
var /** @type {?} */ params = rawParams.split('&');
params.forEach(function (param) {
var /** @type {?} */ eqIdx = param.indexOf('=');
var _a = eqIdx == -1 ? [param, ''] : [param.slice(0, eqIdx), param.slice(eqIdx + 1)], key = _a[0], val = _a[1];
var /** @type {?} */ list = map.get(key) || [];
list.push(val);
map.set(key, list);
});
}
return map;
}
/**
* \@experimental
*
*/
var QueryEncoder = (function () {
function QueryEncoder() {
}
/**
* @param {?} k
* @return {?}
*/
QueryEncoder.prototype.encodeKey = function (k) { return standardEncoding(k); };
/**
* @param {?} v
* @return {?}
*/
QueryEncoder.prototype.encodeValue = function (v) { return standardEncoding(v); };
return QueryEncoder;
}());
/**
* @param {?} v
* @return {?}
*/
function standardEncoding(v) {
return encodeURIComponent(v)
.replace(/%40/gi, '@')
.replace(/%3A/gi, ':')
.replace(/%24/gi, '$')
.replace(/%2C/gi, ',')
.replace(/%3B/gi, ';')
.replace(/%2B/gi, '+')
.replace(/%3D/gi, '=')
.replace(/%3F/gi, '?')
.replace(/%2F/gi, '/');
}
/**
* Map-like representation of url search parameters, based on
* [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams) in the url living standard,
* with several extensions for merging URLSearchParams objects:
* - setAll()
* - appendAll()
* - replaceAll()
*
* This class accepts an optional second parameter of ${\@link QueryEncoder},
* which is used to serialize parameters before making a request. By default,
* `QueryEncoder` encodes keys and values of parameters using `encodeURIComponent`,
* and then un-encodes certain characters that are allowed to be part of the query
* according to IETF RFC 3986: https://tools.ietf.org/html/rfc3986.
*
* These are the characters that are not encoded: `! $ \' ( ) * + , ; A 9 - . _ ~ ? /`
*
* If the set of allowed query characters is not acceptable for a particular backend,
* `QueryEncoder` can be subclassed and provided as the 2nd argument to URLSearchParams.
*
* ```
* import {URLSearchParams, QueryEncoder} from '\@angular/http';
* class MyQueryEncoder extends QueryEncoder {
* encodeKey(k: string): string {
* return myEncodingFunction(k);
* }
*
* encodeValue(v: string): string {
* return myEncodingFunction(v);
* }
* }
*
* let params = new URLSearchParams('', new MyQueryEncoder());
* ```
* \@experimental
*/
var URLSearchParams = (function () {
/**
* @param {?=} rawParams
* @param {?=} queryEncoder
*/
function URLSearchParams(rawParams, queryEncoder) {
if (rawParams === void 0) { rawParams = ''; }
if (queryEncoder === void 0) { queryEncoder = new QueryEncoder(); }
this.rawParams = rawParams;
this.queryEncoder = queryEncoder;
this.paramsMap = paramParser(rawParams);
}
/**
* @return {?}
*/
URLSearchParams.prototype.clone = function () {
var /** @type {?} */ clone = new URLSearchParams('', this.queryEncoder);
clone.appendAll(this);
return clone;
};
/**
* @param {?} param
* @return {?}
*/
URLSearchParams.prototype.has = function (param) { return this.paramsMap.has(param); };
/**
* @param {?} param
* @return {?}
*/
URLSearchParams.prototype.get = function (param) {
var /** @type {?} */ storedParam = this.paramsMap.get(param);
return Array.isArray(storedParam) ? storedParam[0] : null;
};
/**
* @param {?} param
* @return {?}
*/
URLSearchParams.prototype.getAll = function (param) { return this.paramsMap.get(param) || []; };
/**
* @param {?} param
* @param {?} val
* @return {?}
*/
URLSearchParams.prototype.set = function (param, val) {
if (val === void 0 || val === null) {
this.delete(param);
return;
}
var /** @type {?} */ list = this.paramsMap.get(param) || [];
list.length = 0;
list.push(val);
this.paramsMap.set(param, list);
};
/**
* @param {?} searchParams
* @return {?}
*/
URLSearchParams.prototype.setAll = function (searchParams) {
var _this = this;
searchParams.paramsMap.forEach(function (value, param) {
var /** @type {?} */ list = _this.paramsMap.get(param) || [];
list.length = 0;
list.push(value[0]);
_this.paramsMap.set(param, list);
});
};
/**
* @param {?} param
* @param {?} val
* @return {?}
*/
URLSearchParams.prototype.append = function (param, val) {
if (val === void 0 || val === null)
return;
var /** @type {?} */ list = this.paramsMap.get(param) || [];
list.push(val);
this.paramsMap.set(param, list);
};
/**
* @param {?} searchParams
* @return {?}
*/
URLSearchParams.prototype.appendAll = function (searchParams) {
var _this = this;
searchParams.paramsMap.forEach(function (value, param) {
var /** @type {?} */ list = _this.paramsMap.get(param) || [];
for (var /** @type {?} */ i = 0; i < value.length; ++i) {
list.push(value[i]);
}
_this.paramsMap.set(param, list);
});
};
/**
* @param {?} searchParams
* @return {?}
*/
URLSearchParams.prototype.replaceAll = function (searchParams) {
var _this = this;
searchParams.paramsMap.forEach(function (value, param) {
var /** @type {?} */ list = _this.paramsMap.get(param) || [];
list.length = 0;
for (var /** @type {?} */ i = 0; i < value.length; ++i) {
list.push(value[i]);
}
_this.paramsMap.set(param, list);
});
};
/**
* @return {?}
*/
URLSearchParams.prototype.toString = function () {
var _this = this;
var /** @type {?} */ paramsList = [];
this.paramsMap.forEach(function (values, k) {
values.forEach(function (v) { return paramsList.push(_this.queryEncoder.encodeKey(k) + '=' + _this.queryEncoder.encodeValue(v)); });
});
return paramsList.join('&');
};
/**
* @param {?} param
* @return {?}
*/
URLSearchParams.prototype.delete = function (param) { this.paramsMap.delete(param); };
return URLSearchParams;
}());
/**
* @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
*/
/**
* HTTP request body used by both {\@link Request} and {\@link Response}
* https://fetch.spec.whatwg.org/#body
* @abstract
*/
var Body = (function () {
function Body() {
}
/**
* Attempts to return body as parsed `JSON` object, or raises an exception.
* @return {?}
*/
Body.prototype.json = function () {
if (typeof this._body === 'string') {
return JSON.parse(/** @type {?} */ (this._body));
}
if (this._body instanceof ArrayBuffer) {
return JSON.parse(this.text());
}
return this._body;
};
/**
* Returns the body as a string, presuming `toString()` can be called on the response body.
* @return {?}
*/
Body.prototype.text = function () {
if (this._body instanceof URLSearchParams) {
return this._body.toString();
}
if (this._body instanceof ArrayBuffer) {
return String.fromCharCode.apply(null, new Uint16Array(/** @type {?} */ (this._body)));
}
if (this._body == null) {
return '';
}
if (typeof this._body === 'object') {
return JSON.stringify(this._body, null, 2);
}
return this._body.toString();
};
/**
* Return the body as an ArrayBuffer
* @return {?}
*/
Body.prototype.arrayBuffer = function () {
if (this._body instanceof ArrayBuffer) {
return (this._body);
}
return stringToArrayBuffer(this.text());
};
/**
* Returns the request's body as a Blob, assuming that body exists.
* @return {?}
*/
Body.prototype.blob = function () {
if (this._body instanceof Blob) {
return (this._body);
}
if (this._body instanceof ArrayBuffer) {
return new Blob([this._body]);
}
throw new Error('The request body isn\'t either a blob or an array buffer');
};
return Body;
}());
/**
* @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
*/
/**
* Creates `Response` instances from provided values.
*
* Though this object isn't
* usually instantiated by end-users, it is the primary object interacted with when it comes time to
* add data to a view.
*
* ### Example
*
* ```
* http.request('my-friends.txt').subscribe(response => this.friends = response.text());
* ```
*
* The Response's interface is inspired by the Response constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#response-class), but is considered a static value whose body
* can be accessed many times. There are other differences in the implementation, but this is the
* most significant.
*
* \@experimental
*/
var Response = (function (_super) {
__extends(Response, _super);
/**
* @param {?} responseOptions
*/
function Response(responseOptions) {
var _this = _super.call(this) || this;
_this._body = responseOptions.body;
_this.status = responseOptions.status;
_this.ok = (_this.status >= 200 && _this.status <= 299);
_this.statusText = responseOptions.statusText;
_this.headers = responseOptions.headers;
_this.type = responseOptions.type;
_this.url = responseOptions.url;
return _this;
}
/**
* @return {?}
*/
Response.prototype.toString = function () {
return "Response with status: " + this.status + " " + this.statusText + " for URL: " + this.url;
};
return Response;
}(Body));
/**
* @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
*/
var _nextRequestId = 0;
var JSONP_HOME = '__ng_jsonp__';
var _jsonpConnections = null;
/**
* @return {?}
*/
function _getJsonpConnections() {
var /** @type {?} */ w = typeof window == 'object' ? window : {};
if (_jsonpConnections === null) {
_jsonpConnections = w[JSONP_HOME] = {};
}
return _jsonpConnections;
}
var BrowserJsonp = (function () {
function BrowserJsonp() {
}
/**
* @param {?} url
* @return {?}
*/
BrowserJsonp.prototype.build = function (url) {
var /** @type {?} */ node = document.createElement('script');
node.src = url;
return node;
};
/**
* @return {?}
*/
BrowserJsonp.prototype.nextRequestID = function () { return "__req" + _nextRequestId++; };
/**
* @param {?} id
* @return {?}
*/
BrowserJsonp.prototype.requestCallback = function (id) { return JSONP_HOME + "." + id + ".finished"; };
/**
* @param {?} id
* @param {?} connection
* @return {?}
*/
BrowserJsonp.prototype.exposeConnection = function (id, connection) {
var /** @type {?} */ connections = _getJsonpConnections();
connections[id] = connection;
};
/**
* @param {?} id
* @return {?}
*/
BrowserJsonp.prototype.removeConnection = function (id) {
var /** @type {?} */ connections = _getJsonpConnections();
connections[id] = null;
};
/**
* @param {?} node
* @return {?}
*/
BrowserJsonp.prototype.send = function (node) { document.body.appendChild(/** @type {?} */ ((node))); };
/**
* @param {?} node
* @return {?}
*/
BrowserJsonp.prototype.cleanup = function (node) {
if (node.parentNode) {
node.parentNode.removeChild(/** @type {?} */ ((node)));
}
};
return BrowserJsonp;
}());
BrowserJsonp.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
BrowserJsonp.ctorParameters = function () { return []; };
/**
* @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
*/
var JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
var JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';
/**
* Abstract base class for an in-flight JSONP request.
*
* \@experimental
* @abstract
*/
var JSONPConnection = (function () {
function JSONPConnection() {
}
/**
* Callback called when the JSONP request completes, to notify the application
* of the new data.
* @abstract
* @param {?=} data
* @return {?}
*/
JSONPConnection.prototype.finished = function (data) { };
return JSONPConnection;
}());
var JSONPConnection_ = (function (_super) {
__extends(JSONPConnection_, _super);
/**
* @param {?} req
* @param {?} _dom
* @param {?=} baseResponseOptions
*/
function JSONPConnection_(req, _dom, baseResponseOptions) {
var _this = _super.call(this) || this;
_this._dom = _dom;
_this.baseResponseOptions = baseResponseOptions;
_this._finished = false;
if (req.method !== RequestMethod.Get) {
throw new TypeError(JSONP_ERR_WRONG_METHOD);
}
_this.request = req;
_this.response = new __WEBPACK_IMPORTED_MODULE_1_rxjs_Observable__["Observable"](function (responseObserver) {
_this.readyState = ReadyState.Loading;
var id = _this._id = _dom.nextRequestID();
_dom.exposeConnection(id, _this);
// Workaround Dart
// url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
var callback = _dom.requestCallback(_this._id);
var url = req.url;
if (url.indexOf('=JSONP_CALLBACK&') > -1) {
url = url.replace('=JSONP_CALLBACK&', "=" + callback + "&");
}
else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
url = url.substring(0, url.length - '=JSONP_CALLBACK'.length) + ("=" + callback);
}
var script = _this._script = _dom.build(url);
var onLoad = function (event) {
if (_this.readyState === ReadyState.Cancelled)
return;
_this.readyState = ReadyState.Done;
_dom.cleanup(script);
if (!_this._finished) {
var responseOptions_1 = new ResponseOptions({ body: JSONP_ERR_NO_CALLBACK, type: ResponseType.Error, url: url });
if (baseResponseOptions) {
responseOptions_1 = baseResponseOptions.merge(responseOptions_1);
}
responseObserver.error(new Response(responseOptions_1));
return;
}
var responseOptions = new ResponseOptions({ body: _this._responseData, url: url });
if (_this.baseResponseOptions) {
responseOptions = _this.baseResponseOptions.merge(responseOptions);
}
responseObserver.next(new Response(responseOptions));
responseObserver.complete();
};
var onError = function (error) {
if (_this.readyState === ReadyState.Cancelled)
return;
_this.readyState = ReadyState.Done;
_dom.cleanup(script);
var responseOptions = new ResponseOptions({ body: error.message, type: ResponseType.Error });
if (baseResponseOptions) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
responseObserver.error(new Response(responseOptions));
};
script.addEventListener('load', onLoad);
script.addEventListener('error', onError);
_dom.send(script);
return function () {
_this.readyState = ReadyState.Cancelled;
script.removeEventListener('load', onLoad);
script.removeEventListener('error', onError);
_this._dom.cleanup(script);
};
});
return _this;
}
/**
* @param {?=} data
* @return {?}
*/
JSONPConnection_.prototype.finished = function (data) {
// Don't leak connections
this._finished = true;
this._dom.removeConnection(this._id);
if (this.readyState === ReadyState.Cancelled)
return;
this._responseData = data;
};
return JSONPConnection_;
}(JSONPConnection));
/**
* A {\@link ConnectionBackend} that uses the JSONP strategy of making requests.
*
* \@experimental
* @abstract
*/
var JSONPBackend = (function (_super) {
__extends(JSONPBackend, _super);
function JSONPBackend() {
return _super !== null && _super.apply(this, arguments) || this;
}
return JSONPBackend;
}(ConnectionBackend));
var JSONPBackend_ = (function (_super) {
__extends(JSONPBackend_, _super);
/**
* @param {?} _browserJSONP
* @param {?} _baseResponseOptions
*/
function JSONPBackend_(_browserJSONP, _baseResponseOptions) {
var _this = _super.call(this) || this;
_this._browserJSONP = _browserJSONP;
_this._baseResponseOptions = _baseResponseOptions;
return _this;
}
/**
* @param {?} request
* @return {?}
*/
JSONPBackend_.prototype.createConnection = function (request) {
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
};
return JSONPBackend_;
}(JSONPBackend));
JSONPBackend_.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
JSONPBackend_.ctorParameters = function () { return [
{ type: BrowserJsonp, },
{ type: ResponseOptions, },
]; };
/**
* @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
*/
var XSSI_PREFIX = /^\)\]\}',?\n/;
/**
* Creates connections using `XMLHttpRequest`. Given a fully-qualified
* request, an `XHRConnection` will immediately create an `XMLHttpRequest` object and send the
* request.
*
* This class would typically not be created or interacted with directly inside applications, though
* the {\@link MockConnection} may be interacted with in tests.
*
* \@experimental
*/
var XHRConnection = (function () {
/**
* @param {?} req
* @param {?} browserXHR
* @param {?=} baseResponseOptions
*/
function XHRConnection(req, browserXHR, baseResponseOptions) {
var _this = this;
this.request = req;
this.response = new __WEBPACK_IMPORTED_MODULE_1_rxjs_Observable__["Observable"](function (responseObserver) {
var _xhr = browserXHR.build();
_xhr.open(RequestMethod[req.method].toUpperCase(), req.url);
if (req.withCredentials != null) {
_xhr.withCredentials = req.withCredentials;
}
// load event handler
var onLoad = function () {
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = _xhr.status === 1223 ? 204 : _xhr.status;
var body = null;
// HTTP 204 means no content
if (status !== 204) {
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in ResourceLoader Level2 spec
// (supported by IE10)
body = (typeof _xhr.response === 'undefined') ? _xhr.responseText : _xhr.response;
// Implicitly strip a potential XSSI prefix.
if (typeof body === 'string') {
body = body.replace(XSSI_PREFIX, '');
}
}
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = body ? 200 : 0;
}
var headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders());
// IE 9 does not provide the way to get URL of response
var url = getResponseURL(_xhr) || req.url;
var statusText = _xhr.statusText || 'OK';
var responseOptions = new ResponseOptions({ body: body, status: status, headers: headers, statusText: statusText, url: url });
if (baseResponseOptions != null) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
var response = new Response(responseOptions);
response.ok = isSuccess(status);
if (response.ok) {
responseObserver.next(response);
// TODO(gdi2290): defer complete if array buffer until done
responseObserver.complete();
return;
}
responseObserver.error(response);
};
// error event handler
var onError = function (err) {
var responseOptions = new ResponseOptions({
body: err,
type: ResponseType.Error,
status: _xhr.status,
statusText: _xhr.statusText,
});
if (baseResponseOptions != null) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
responseObserver.error(new Response(responseOptions));
};
_this.setDetectedContentType(req, _xhr);
if (req.headers == null) {
req.headers = new Headers();
}
if (!req.headers.has('Accept')) {
req.headers.append('Accept', 'application/json, text/plain, */*');
}
req.headers.forEach(function (values, name) { return _xhr.setRequestHeader(name, values.join(',')); });
// Select the correct buffer type to store the response
if (req.responseType != null && _xhr.responseType != null) {
switch (req.responseType) {
case ResponseContentType.ArrayBuffer:
_xhr.responseType = 'arraybuffer';
break;
case ResponseContentType.Json:
_xhr.responseType = 'json';
break;
case ResponseContentType.Text:
_xhr.responseType = 'text';
break;
case ResponseContentType.Blob:
_xhr.responseType = 'blob';
break;
default:
throw new Error('The selected responseType is not supported');
}
}
_xhr.addEventListener('load', onLoad);
_xhr.addEventListener('error', onError);
_xhr.send(_this.request.getBody());
return function () {
_xhr.removeEventListener('load', onLoad);
_xhr.removeEventListener('error', onError);
_xhr.abort();
};
});
}
/**
* @param {?} req
* @param {?} _xhr
* @return {?}
*/
XHRConnection.prototype.setDetectedContentType = function (req /** TODO Request */, _xhr /** XMLHttpRequest */) {
// Skip if a custom Content-Type header is provided
if (req.headers != null && req.headers.get('Content-Type') != null) {
return;
}
// Set the detected content type
switch (req.contentType) {
case ContentType.NONE:
break;
case ContentType.JSON:
_xhr.setRequestHeader('content-type', 'application/json');
break;
case ContentType.FORM:
_xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
break;
case ContentType.TEXT:
_xhr.setRequestHeader('content-type', 'text/plain');
break;
case ContentType.BLOB:
var /** @type {?} */ blob = req.blob();
if (blob.type) {
_xhr.setRequestHeader('content-type', blob.type);
}
break;
}
};
return XHRConnection;
}());
/**
* `XSRFConfiguration` sets up Cross Site Request Forgery (XSRF) protection for the application
* using a cookie. See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
* for more information on XSRF.
*
* Applications can configure custom cookie and header names by binding an instance of this class
* with different `cookieName` and `headerName` values. See the main HTTP documentation for more
* details.
*
* \@experimental
*/
var CookieXSRFStrategy = (function () {
/**
* @param {?=} _cookieName
* @param {?=} _headerName
*/
function CookieXSRFStrategy(_cookieName, _headerName) {
if (_cookieName === void 0) { _cookieName = 'XSRF-TOKEN'; }
if (_headerName === void 0) { _headerName = 'X-XSRF-TOKEN'; }
this._cookieName = _cookieName;
this._headerName = _headerName;
}
/**
* @param {?} req
* @return {?}
*/
CookieXSRFStrategy.prototype.configureRequest = function (req) {
var /** @type {?} */ xsrfToken = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__angular_platform_browser__["c" /* ɵgetDOM */])().getCookie(this._cookieName);
if (xsrfToken) {
req.headers.set(this._headerName, xsrfToken);
}
};
return CookieXSRFStrategy;
}());
/**
* Creates {\@link XHRConnection} instances.
*
* This class would typically not be used by end users, but could be
* overridden if a different backend implementation should be used,
* such as in a node backend.
*
* ### Example
*
* ```
* import {Http, MyNodeBackend, HTTP_PROVIDERS, BaseRequestOptions} from '\@angular/http';
* \@Component({
* viewProviders: [
* HTTP_PROVIDERS,
* {provide: Http, useFactory: (backend, options) => {
* return new Http(backend, options);
* }, deps: [MyNodeBackend, BaseRequestOptions]}]
* })
* class MyComponent {
* constructor(http:Http) {
* http.request('people.json').subscribe(res => this.people = res.json());
* }
* }
* ```
* \@experimental
*/
var XHRBackend = (function () {
/**
* @param {?} _browserXHR
* @param {?} _baseResponseOptions
* @param {?} _xsrfStrategy
*/
function XHRBackend(_browserXHR, _baseResponseOptions, _xsrfStrategy) {
this._browserXHR = _browserXHR;
this._baseResponseOptions = _baseResponseOptions;
this._xsrfStrategy = _xsrfStrategy;
}
/**
* @param {?} request
* @return {?}
*/
XHRBackend.prototype.createConnection = function (request) {
this._xsrfStrategy.configureRequest(request);
return new XHRConnection(request, this._browserXHR, this._baseResponseOptions);
};
return XHRBackend;
}());
XHRBackend.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
XHRBackend.ctorParameters = function () { return [
{ type: BrowserXhr, },
{ type: ResponseOptions, },
{ type: XSRFStrategy, },
]; };
/**
* @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
*/
/**
* Creates a request options object to be optionally provided when instantiating a
* {\@link Request}.
*
* This class is based on the `RequestInit` description in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#requestinit).
*
* All values are null by default. Typical defaults can be found in the {\@link BaseRequestOptions}
* class, which sub-classes `RequestOptions`.
*
* ```typescript
* import {RequestOptions, Request, RequestMethod} from '\@angular/http';
*
* const options = new RequestOptions({
* method: RequestMethod.Post,
* url: 'https://google.com'
* });
* const req = new Request(options);
* console.log('req.method:', RequestMethod[req.method]); // Post
* console.log('options.url:', options.url); // https://google.com
* ```
*
* \@experimental
*/
var RequestOptions = (function () {
/**
* @param {?=} __0
*/
function RequestOptions(_a) {
var _b = _a === void 0 ? {} : _a, method = _b.method, headers = _b.headers, body = _b.body, url = _b.url, search = _b.search, params = _b.params, withCredentials = _b.withCredentials, responseType = _b.responseType;
this.method = method != null ? normalizeMethodName(method) : null;
this.headers = headers != null ? headers : null;
this.body = body != null ? body : null;
this.url = url != null ? url : null;
this.params = this._mergeSearchParams(params || search);
this.withCredentials = withCredentials != null ? withCredentials : null;
this.responseType = responseType != null ? responseType : null;
}
Object.defineProperty(RequestOptions.prototype, "search", {
/**
* @deprecated from 4.0.0. Use params instead.
* @return {?}
*/
get: function () { return this.params; },
/**
* @deprecated from 4.0.0. Use params instead.
* @param {?} params
* @return {?}
*/
set: function (params) { this.params = params; },
enumerable: true,
configurable: true
});
/**
* Creates a copy of the `RequestOptions` instance, using the optional input as values to override
* existing values. This method will not change the values of the instance on which it is being
* called.
*
* Note that `headers` and `search` will override existing values completely if present in
* the `options` object. If these values should be merged, it should be done prior to calling
* `merge` on the `RequestOptions` instance.
*
* ```typescript
* import {RequestOptions, Request, RequestMethod} from '\@angular/http';
*
* const options = new RequestOptions({
* method: RequestMethod.Post
* });
* const req = new Request(options.merge({
* url: 'https://google.com'
* }));
* console.log('req.method:', RequestMethod[req.method]); // Post
* console.log('options.url:', options.url); // null
* console.log('req.url:', req.url); // https://google.com
* ```
* @param {?=} options
* @return {?}
*/
RequestOptions.prototype.merge = function (options) {
return new RequestOptions({
method: options && options.method != null ? options.method : this.method,
headers: options && options.headers != null ? options.headers : new Headers(this.headers),
body: options && options.body != null ? options.body : this.body,
url: options && options.url != null ? options.url : this.url,
params: options && this._mergeSearchParams(options.params || options.search),
withCredentials: options && options.withCredentials != null ? options.withCredentials :
this.withCredentials,
responseType: options && options.responseType != null ? options.responseType :
this.responseType
});
};
/**
* @param {?=} params
* @return {?}
*/
RequestOptions.prototype._mergeSearchParams = function (params) {
if (!params)
return this.params;
if (params instanceof URLSearchParams) {
return params.clone();
}
if (typeof params === 'string') {
return new URLSearchParams(params);
}
return this._parseParams(params);
};
/**
* @param {?=} objParams
* @return {?}
*/
RequestOptions.prototype._parseParams = function (objParams) {
var _this = this;
if (objParams === void 0) { objParams = {}; }
var /** @type {?} */ params = new URLSearchParams();
Object.keys(objParams).forEach(function (key) {
var /** @type {?} */ value = objParams[key];
if (Array.isArray(value)) {
value.forEach(function (item) { return _this._appendParam(key, item, params); });
}
else {
_this._appendParam(key, value, params);
}
});
return params;
};
/**
* @param {?} key
* @param {?} value
* @param {?} params
* @return {?}
*/
RequestOptions.prototype._appendParam = function (key, value, params) {
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
params.append(key, value);
};
return RequestOptions;
}());
/**
* Subclass of {\@link RequestOptions}, with default values.
*
* Default values:
* * method: {\@link RequestMethod RequestMethod.Get}
* * headers: empty {\@link Headers} object
*
* This class could be extended and bound to the {\@link RequestOptions} class
* when configuring an {\@link Injector}, in order to override the default options
* used by {\@link Http} to create and send {\@link Request Requests}.
*
* ```typescript
* import {BaseRequestOptions, RequestOptions} from '\@angular/http';
*
* class MyOptions extends BaseRequestOptions {
* search: string = 'coreTeam=true';
* }
*
* {provide: RequestOptions, useClass: MyOptions};
* ```
*
* The options could also be extended when manually creating a {\@link Request}
* object.
*
* ```
* import {BaseRequestOptions, Request, RequestMethod} from '\@angular/http';
*
* const options = new BaseRequestOptions();
* const req = new Request(options.merge({
* method: RequestMethod.Post,
* url: 'https://google.com'
* }));
* console.log('req.method:', RequestMethod[req.method]); // Post
* console.log('options.url:', options.url); // null
* console.log('req.url:', req.url); // https://google.com
* ```
*
* \@experimental
*/
var BaseRequestOptions = (function (_super) {
__extends(BaseRequestOptions, _super);
function BaseRequestOptions() {
return _super.call(this, { method: RequestMethod.Get, headers: new Headers() }) || this;
}
return BaseRequestOptions;
}(RequestOptions));
BaseRequestOptions.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
BaseRequestOptions.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* Creates `Request` instances from provided values.
*
* The Request's interface is inspired by the Request constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#request-class),
* but is considered a static value whose body can be accessed many times. There are other
* differences in the implementation, but this is the most significant.
*
* `Request` instances are typically created by higher-level classes, like {\@link Http} and
* {\@link Jsonp}, but it may occasionally be useful to explicitly create `Request` instances.
* One such example is when creating services that wrap higher-level services, like {\@link Http},
* where it may be useful to generate a `Request` with arbitrary headers and search params.
*
* ```typescript
* import {Injectable, Injector} from '\@angular/core';
* import {HTTP_PROVIDERS, Http, Request, RequestMethod} from '\@angular/http';
*
* \@Injectable()
* class AutoAuthenticator {
* constructor(public http:Http) {}
* request(url:string) {
* return this.http.request(new Request({
* method: RequestMethod.Get,
* url: url,
* search: 'password=123'
* }));
* }
* }
*
* var injector = Injector.resolveAndCreate([HTTP_PROVIDERS, AutoAuthenticator]);
* var authenticator = injector.get(AutoAuthenticator);
* authenticator.request('people.json').subscribe(res => {
* //URL should have included '?password=123'
* console.log('people', res.json());
* });
* ```
*
* \@experimental
*/
var Request = (function (_super) {
__extends(Request, _super);
/**
* @param {?} requestOptions
*/
function Request(requestOptions) {
var _this = _super.call(this) || this;
// TODO: assert that url is present
var url = requestOptions.url;
_this.url = requestOptions.url;
if (requestOptions.params) {
var params = requestOptions.params.toString();
if (params.length > 0) {
var prefix = '?';
if (_this.url.indexOf('?') != -1) {
prefix = (_this.url[_this.url.length - 1] == '&') ? '' : '&';
}
// TODO: just delete search-query-looking string in url?
_this.url = url + prefix + params;
}
}
_this._body = requestOptions.body;
_this.method = normalizeMethodName(requestOptions.method);
// TODO(jeffbcross): implement behavior
// Defaults to 'omit', consistent with browser
_this.headers = new Headers(requestOptions.headers);
_this.contentType = _this.detectContentType();
_this.withCredentials = requestOptions.withCredentials;
_this.responseType = requestOptions.responseType;
return _this;
}
/**
* Returns the content type enum based on header options.
* @return {?}
*/
Request.prototype.detectContentType = function () {
switch (this.headers.get('content-type')) {
case 'application/json':
return ContentType.JSON;
case 'application/x-www-form-urlencoded':
return ContentType.FORM;
case 'multipart/form-data':
return ContentType.FORM_DATA;
case 'text/plain':
case 'text/html':
return ContentType.TEXT;
case 'application/octet-stream':
return this._body instanceof ArrayBuffer$1 ? ContentType.ARRAY_BUFFER : ContentType.BLOB;
default:
return this.detectContentTypeFromBody();
}
};
/**
* Returns the content type of request's body based on its type.
* @return {?}
*/
Request.prototype.detectContentTypeFromBody = function () {
if (this._body == null) {
return ContentType.NONE;
}
else if (this._body instanceof URLSearchParams) {
return ContentType.FORM;
}
else if (this._body instanceof FormData) {
return ContentType.FORM_DATA;
}
else if (this._body instanceof Blob$1) {
return ContentType.BLOB;
}
else if (this._body instanceof ArrayBuffer$1) {
return ContentType.ARRAY_BUFFER;
}
else if (this._body && typeof this._body === 'object') {
return ContentType.JSON;
}
else {
return ContentType.TEXT;
}
};
/**
* Returns the request's body according to its type. If body is undefined, return
* null.
* @return {?}
*/
Request.prototype.getBody = function () {
switch (this.contentType) {
case ContentType.JSON:
return this.text();
case ContentType.FORM:
return this.text();
case ContentType.FORM_DATA:
return this._body;
case ContentType.TEXT:
return this.text();
case ContentType.BLOB:
return this.blob();
case ContentType.ARRAY_BUFFER:
return this.arrayBuffer();
default:
return null;
}
};
return Request;
}(Body));
var noop = function () { };
var w = typeof window == 'object' ? window : noop;
var FormData = ((w) /** TODO #9100 */)['FormData'] || noop;
var Blob$1 = ((w) /** TODO #9100 */)['Blob'] || noop;
var ArrayBuffer$1 = ((w) /** TODO #9100 */)['ArrayBuffer'] || noop;
/**
* @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
*/
/**
* @param {?} backend
* @param {?} request
* @return {?}
*/
function httpRequest(backend, request) {
return backend.createConnection(request).response;
}
/**
* @param {?} defaultOpts
* @param {?} providedOpts
* @param {?} method
* @param {?} url
* @return {?}
*/
function mergeOptions(defaultOpts, providedOpts, method, url) {
var /** @type {?} */ newOptions = defaultOpts;
if (providedOpts) {
// Hack so Dart can used named parameters
return (newOptions.merge(new RequestOptions({
method: providedOpts.method || method,
url: providedOpts.url || url,
search: providedOpts.search,
params: providedOpts.params,
headers: providedOpts.headers,
body: providedOpts.body,
withCredentials: providedOpts.withCredentials,
responseType: providedOpts.responseType
})));
}
return (newOptions.merge(new RequestOptions({ method: method, url: url })));
}
/**
* Performs http requests using `XMLHttpRequest` as the default backend.
*
* `Http` is available as an injectable class, with methods to perform http requests. Calling
* `request` returns an `Observable` which will emit a single {\@link Response} when a
* response is received.
*
* ### Example
*
* ```typescript
* import {Http, HTTP_PROVIDERS} from '\@angular/http';
* import 'rxjs/add/operator/map'
* \@Component({
* selector: 'http-app',
* viewProviders: [HTTP_PROVIDERS],
* templateUrl: 'people.html'
* })
* class PeopleComponent {
* constructor(http: Http) {
* http.get('people.json')
* // Call map on the response observable to get the parsed people object
* .map(res => res.json())
* // Subscribe to the observable to get the parsed people object and attach it to the
* // component
* .subscribe(people => this.people = people);
* }
* }
* ```
*
*
* ### Example
*
* ```
* http.get('people.json').subscribe((res:Response) => this.people = res.json());
* ```
*
* The default construct used to perform requests, `XMLHttpRequest`, is abstracted as a "Backend" (
* {\@link XHRBackend} in this case), which could be mocked with dependency injection by replacing
* the {\@link XHRBackend} provider, as in the following example:
*
* ### Example
*
* ```typescript
* import {BaseRequestOptions, Http} from '\@angular/http';
* import {MockBackend} from '\@angular/http/testing';
* var injector = Injector.resolveAndCreate([
* BaseRequestOptions,
* MockBackend,
* {provide: Http, useFactory:
* function(backend, defaultOptions) {
* return new Http(backend, defaultOptions);
* },
* deps: [MockBackend, BaseRequestOptions]}
* ]);
* var http = injector.get(Http);
* http.get('request-from-mock-backend.json').subscribe((res:Response) => doSomething(res));
* ```
*
* \@experimental
*/
var Http = (function () {
/**
* @param {?} _backend
* @param {?} _defaultOptions
*/
function Http(_backend, _defaultOptions) {
this._backend = _backend;
this._defaultOptions = _defaultOptions;
}
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {\@link Request} instance. If the first argument is a url, an optional {\@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {\@link BaseRequestOptions} before performing the request.
* @param {?} url
* @param {?=} options
* @return {?}
*/
Http.prototype.request = function (url, options) {
var /** @type {?} */ responseObservable;
if (typeof url === 'string') {
responseObservable = httpRequest(this._backend, new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, /** @type {?} */ (url))));
}
else if (url instanceof Request) {
responseObservable = httpRequest(this._backend, url);
}
else {
throw new Error('First argument must be a url string or Request instance.');
}
return responseObservable;
};
/**
* Performs a request with `get` http method.
* @param {?} url
* @param {?=} options
* @return {?}
*/
Http.prototype.get = function (url, options) {
return this.request(new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, url)));
};
/**
* Performs a request with `post` http method.
* @param {?} url
* @param {?} body
* @param {?=} options
* @return {?}
*/
Http.prototype.post = function (url, body, options) {
return this.request(new Request(mergeOptions(this._defaultOptions.merge(new RequestOptions({ body: body })), options, RequestMethod.Post, url)));
};
/**
* Performs a request with `put` http method.
* @param {?} url
* @param {?} body
* @param {?=} options
* @return {?}
*/
Http.prototype.put = function (url, body, options) {
return this.request(new Request(mergeOptions(this._defaultOptions.merge(new RequestOptions({ body: body })), options, RequestMethod.Put, url)));
};
/**
* Performs a request with `delete` http method.
* @param {?} url
* @param {?=} options
* @return {?}
*/
Http.prototype.delete = function (url, options) {
return this.request(new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Delete, url)));
};
/**
* Performs a request with `patch` http method.
* @param {?} url
* @param {?} body
* @param {?=} options
* @return {?}
*/
Http.prototype.patch = function (url, body, options) {
return this.request(new Request(mergeOptions(this._defaultOptions.merge(new RequestOptions({ body: body })), options, RequestMethod.Patch, url)));
};
/**
* Performs a request with `head` http method.
* @param {?} url
* @param {?=} options
* @return {?}
*/
Http.prototype.head = function (url, options) {
return this.request(new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Head, url)));
};
/**
* Performs a request with `options` http method.
* @param {?} url
* @param {?=} options
* @return {?}
*/
Http.prototype.options = function (url, options) {
return this.request(new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Options, url)));
};
return Http;
}());
Http.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
Http.ctorParameters = function () { return [
{ type: ConnectionBackend, },
{ type: RequestOptions, },
]; };
/**
* \@experimental
*/
var Jsonp = (function (_super) {
__extends(Jsonp, _super);
/**
* @param {?} backend
* @param {?} defaultOptions
*/
function Jsonp(backend, defaultOptions) {
return _super.call(this, backend, defaultOptions) || this;
}
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {\@link Request} instance. If the first argument is a url, an optional {\@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {\@link BaseRequestOptions} before performing the request.
*
* \@security Regular XHR is the safest alternative to JSONP for most applications, and is
* supported by all current browsers. Because JSONP creates a `<script>` element with
* contents retrieved from a remote source, attacker-controlled data introduced by an untrusted
* source could expose your application to XSS risks. Data exposed by JSONP may also be
* readable by malicious third-party websites. In addition, JSONP introduces potential risk for
* future security issues (e.g. content sniffing). For more detail, see the
* [Security Guide](http://g.co/ng/security).
* @param {?} url
* @param {?=} options
* @return {?}
*/
Jsonp.prototype.request = function (url, options) {
var /** @type {?} */ responseObservable;
if (typeof url === 'string') {
url =
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, /** @type {?} */ (url)));
}
if (url instanceof Request) {
if (url.method !== RequestMethod.Get) {
throw new Error('JSONP requests must use GET request method.');
}
responseObservable = httpRequest(this._backend, url);
}
else {
throw new Error('First argument must be a url string or Request instance.');
}
return responseObservable;
};
return Jsonp;
}(Http));
Jsonp.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
Jsonp.ctorParameters = function () { return [
{ type: ConnectionBackend, },
{ type: RequestOptions, },
]; };
/**
* @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
*/
/**
* @module
* @description
* The http module provides services to perform http requests. To get started, see the {@link Http}
* class.
*/
/**
* @return {?}
*/
function _createDefaultCookieXSRFStrategy() {
return new CookieXSRFStrategy();
}
/**
* @param {?} xhrBackend
* @param {?} requestOptions
* @return {?}
*/
function httpFactory(xhrBackend, requestOptions) {
return new Http(xhrBackend, requestOptions);
}
/**
* @param {?} jsonpBackend
* @param {?} requestOptions
* @return {?}
*/
function jsonpFactory(jsonpBackend, requestOptions) {
return new Jsonp(jsonpBackend, requestOptions);
}
/**
* The module that includes http's providers
*
* \@experimental
*/
var HttpModule = (function () {
function HttpModule() {
}
return HttpModule;
}());
HttpModule.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */], args: [{
providers: [
// TODO(pascal): use factory type annotations once supported in DI
// issue: https://github.com/angular/angular/issues/3183
{ provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions] },
BrowserXhr,
{ provide: RequestOptions, useClass: BaseRequestOptions },
{ provide: ResponseOptions, useClass: BaseResponseOptions },
XHRBackend,
{ provide: XSRFStrategy, useFactory: _createDefaultCookieXSRFStrategy },
],
},] },
];
/**
* @nocollapse
*/
HttpModule.ctorParameters = function () { return []; };
/**
* The module that includes jsonp's providers
*
* \@experimental
*/
var JsonpModule = (function () {
function JsonpModule() {
}
return JsonpModule;
}());
JsonpModule.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */], args: [{
providers: [
// TODO(pascal): use factory type annotations once supported in DI
// issue: https://github.com/angular/angular/issues/3183
{ provide: Jsonp, useFactory: jsonpFactory, deps: [JSONPBackend, RequestOptions] },
BrowserJsonp,
{ provide: RequestOptions, useClass: BaseRequestOptions },
{ provide: ResponseOptions, useClass: BaseResponseOptions },
{ provide: JSONPBackend, useClass: JSONPBackend_ },
],
},] },
];
/**
* @nocollapse
*/
JsonpModule.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
var VERSION = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["u" /* Version */]('4.1.1');
/**
* @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
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the http package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=http.es5.js.map
/***/ }),
/* 14 */,
/* 15 */,
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
if (typeof window == 'object' && window.window === window) {
exports.root = window;
}
else if (typeof self == 'object' && self.self === self) {
exports.root = self;
}
else if (typeof global == 'object' && global.global === global) {
exports.root = global;
}
else {
// Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
// This is needed when used with angular/tsickle which inserts a goog.module statement.
// Wrap in IIFE
(function () {
throw new Error('RxJS could not find any global context (window, self, global)');
})();
}
//# sourceMappingURL=root.js.map
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21)))
/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1);
/* unused harmony export NgLocaleLocalization */
/* unused harmony export NgLocalization */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return CommonModule; });
/* unused harmony export NgClass */
/* unused harmony export NgFor */
/* unused harmony export NgForOf */
/* unused harmony export NgForOfContext */
/* unused harmony export NgIf */
/* unused harmony export NgIfContext */
/* unused harmony export NgPlural */
/* unused harmony export NgPluralCase */
/* unused harmony export NgStyle */
/* unused harmony export NgSwitch */
/* unused harmony export NgSwitchCase */
/* unused harmony export NgSwitchDefault */
/* unused harmony export NgTemplateOutlet */
/* unused harmony export NgComponentOutlet */
/* unused harmony export AsyncPipe */
/* unused harmony export DatePipe */
/* unused harmony export I18nPluralPipe */
/* unused harmony export I18nSelectPipe */
/* unused harmony export JsonPipe */
/* unused harmony export LowerCasePipe */
/* unused harmony export CurrencyPipe */
/* unused harmony export DecimalPipe */
/* unused harmony export PercentPipe */
/* unused harmony export SlicePipe */
/* unused harmony export UpperCasePipe */
/* unused harmony export TitleCasePipe */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PLATFORM_BROWSER_ID; });
/* unused harmony export ɵPLATFORM_SERVER_ID */
/* unused harmony export ɵPLATFORM_WORKER_APP_ID */
/* unused harmony export ɵPLATFORM_WORKER_UI_ID */
/* unused harmony export isPlatformBrowser */
/* unused harmony export isPlatformServer */
/* unused harmony export isPlatformWorkerApp */
/* unused harmony export isPlatformWorkerUi */
/* unused harmony export VERSION */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PlatformLocation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return LOCATION_INITIALIZED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return LocationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return APP_BASE_HREF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return HashLocationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return PathLocationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return Location; });
/* unused harmony export ɵa */
/* unused harmony export ɵb */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.1
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @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
*/
/**
* This class should not be used directly by an application developer. Instead, use
* {\@link Location}.
*
* `PlatformLocation` encapsulates all calls to DOM apis, which allows the Router to be platform
* agnostic.
* This means that we can have different implementation of `PlatformLocation` for the different
* platforms that angular supports. For example, `\@angular/platform-browser` provides an
* implementation specific to the browser environment, while `\@angular/platform-webworker` provides
* one suitable for use with web workers.
*
* The `PlatformLocation` class is used directly by all implementations of {\@link LocationStrategy}
* when they need to interact with the DOM apis like pushState, popState, etc...
*
* {\@link LocationStrategy} in turn is used by the {\@link Location} service which is used directly
* by the {\@link Router} in order to navigate between routes. Since all interactions between {\@link
* Router} /
* {\@link Location} / {\@link LocationStrategy} and DOM apis flow through the `PlatformLocation`
* class they are all platform independent.
*
* \@stable
* @abstract
*/
var PlatformLocation = (function () {
function PlatformLocation() {
}
/**
* @abstract
* @return {?}
*/
PlatformLocation.prototype.getBaseHrefFromDOM = function () { };
/**
* @abstract
* @param {?} fn
* @return {?}
*/
PlatformLocation.prototype.onPopState = function (fn) { };
/**
* @abstract
* @param {?} fn
* @return {?}
*/
PlatformLocation.prototype.onHashChange = function (fn) { };
/**
* @abstract
* @return {?}
*/
PlatformLocation.prototype.pathname = function () { };
/**
* @abstract
* @return {?}
*/
PlatformLocation.prototype.search = function () { };
/**
* @abstract
* @return {?}
*/
PlatformLocation.prototype.hash = function () { };
/**
* @abstract
* @param {?} state
* @param {?} title
* @param {?} url
* @return {?}
*/
PlatformLocation.prototype.replaceState = function (state, title, url) { };
/**
* @abstract
* @param {?} state
* @param {?} title
* @param {?} url
* @return {?}
*/
PlatformLocation.prototype.pushState = function (state, title, url) { };
/**
* @abstract
* @return {?}
*/
PlatformLocation.prototype.forward = function () { };
/**
* @abstract
* @return {?}
*/
PlatformLocation.prototype.back = function () { };
return PlatformLocation;
}());
/**
* \@whatItDoes indicates when a location is initialized
* \@experimental
*/
var LOCATION_INITIALIZED = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('Location Initialized');
/**
* @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
*/
/**
* `LocationStrategy` is responsible for representing and reading route state
* from the browser's URL. Angular provides two strategies:
* {\@link HashLocationStrategy} and {\@link PathLocationStrategy}.
*
* This is used under the hood of the {\@link Location} service.
*
* Applications should use the {\@link Router} or {\@link Location} services to
* interact with application route state.
*
* For instance, {\@link HashLocationStrategy} produces URLs like
* `http://example.com#/foo`, and {\@link PathLocationStrategy} produces
* `http://example.com/foo` as an equivalent URL.
*
* See these two classes for more.
*
* \@stable
* @abstract
*/
var LocationStrategy = (function () {
function LocationStrategy() {
}
/**
* @abstract
* @param {?=} includeHash
* @return {?}
*/
LocationStrategy.prototype.path = function (includeHash) { };
/**
* @abstract
* @param {?} internal
* @return {?}
*/
LocationStrategy.prototype.prepareExternalUrl = function (internal) { };
/**
* @abstract
* @param {?} state
* @param {?} title
* @param {?} url
* @param {?} queryParams
* @return {?}
*/
LocationStrategy.prototype.pushState = function (state, title, url, queryParams) { };
/**
* @abstract
* @param {?} state
* @param {?} title
* @param {?} url
* @param {?} queryParams
* @return {?}
*/
LocationStrategy.prototype.replaceState = function (state, title, url, queryParams) { };
/**
* @abstract
* @return {?}
*/
LocationStrategy.prototype.forward = function () { };
/**
* @abstract
* @return {?}
*/
LocationStrategy.prototype.back = function () { };
/**
* @abstract
* @param {?} fn
* @return {?}
*/
LocationStrategy.prototype.onPopState = function (fn) { };
/**
* @abstract
* @return {?}
*/
LocationStrategy.prototype.getBaseHref = function () { };
return LocationStrategy;
}());
/**
* The `APP_BASE_HREF` token represents the base href to be used with the
* {\@link PathLocationStrategy}.
*
* If you're using {\@link PathLocationStrategy}, you must provide a provider to a string
* representing the URL prefix that should be preserved when generating and recognizing
* URLs.
*
* ### Example
*
* ```typescript
* import {Component, NgModule} from '\@angular/core';
* import {APP_BASE_HREF} from '\@angular/common';
*
* \@NgModule({
* providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
* })
* class AppModule {}
* ```
*
* \@stable
*/
var APP_BASE_HREF = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('appBaseHref');
/**
* @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
*/
/**
* \@whatItDoes `Location` is a service that applications can use to interact with a browser's URL.
* \@description
* Depending on which {\@link LocationStrategy} is used, `Location` will either persist
* to the URL's path or the URL's hash segment.
*
* Note: it's better to use {\@link Router#navigate} service to trigger route changes. Use
* `Location` only if you need to interact with or create normalized URLs outside of
* routing.
*
* `Location` is responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*
* ### Example
* {\@example common/location/ts/path_location_component.ts region='LocationComponent'}
* \@stable
*/
var Location = (function () {
/**
* @param {?} platformStrategy
*/
function Location(platformStrategy) {
var _this = this;
/**
* \@internal
*/
this._subject = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["r" /* EventEmitter */]();
this._platformStrategy = platformStrategy;
var browserBaseHref = this._platformStrategy.getBaseHref();
this._baseHref = Location.stripTrailingSlash(_stripIndexHtml(browserBaseHref));
this._platformStrategy.onPopState(function (ev) {
_this._subject.emit({
'url': _this.path(true),
'pop': true,
'type': ev.type,
});
});
}
/**
* @param {?=} includeHash
* @return {?}
*/
Location.prototype.path = function (includeHash) {
if (includeHash === void 0) { includeHash = false; }
return this.normalize(this._platformStrategy.path(includeHash));
};
/**
* Normalizes the given path and compares to the current normalized path.
* @param {?} path
* @param {?=} query
* @return {?}
*/
Location.prototype.isCurrentPathEqualTo = function (path, query) {
if (query === void 0) { query = ''; }
return this.path() == this.normalize(path + Location.normalizeQueryParams(query));
};
/**
* Given a string representing a URL, returns the normalized URL path without leading or
* trailing slashes.
* @param {?} url
* @return {?}
*/
Location.prototype.normalize = function (url) {
return Location.stripTrailingSlash(_stripBaseHref(this._baseHref, _stripIndexHtml(url)));
};
/**
* Given a string representing a URL, returns the platform-specific external URL path.
* If the given URL doesn't begin with a leading slash (`'/'`), this method adds one
* before normalizing. This method will also add a hash if `HashLocationStrategy` is
* used, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use.
* @param {?} url
* @return {?}
*/
Location.prototype.prepareExternalUrl = function (url) {
if (url && url[0] !== '/') {
url = '/' + url;
}
return this._platformStrategy.prepareExternalUrl(url);
};
/**
* Changes the browsers URL to the normalized version of the given URL, and pushes a
* new item onto the platform's history.
* @param {?} path
* @param {?=} query
* @return {?}
*/
Location.prototype.go = function (path, query) {
if (query === void 0) { query = ''; }
this._platformStrategy.pushState(null, '', path, query);
};
/**
* Changes the browsers URL to the normalized version of the given URL, and replaces
* the top item on the platform's history stack.
* @param {?} path
* @param {?=} query
* @return {?}
*/
Location.prototype.replaceState = function (path, query) {
if (query === void 0) { query = ''; }
this._platformStrategy.replaceState(null, '', path, query);
};
/**
* Navigates forward in the platform's history.
* @return {?}
*/
Location.prototype.forward = function () { this._platformStrategy.forward(); };
/**
* Navigates back in the platform's history.
* @return {?}
*/
Location.prototype.back = function () { this._platformStrategy.back(); };
/**
* Subscribe to the platform's `popState` events.
* @param {?} onNext
* @param {?=} onThrow
* @param {?=} onReturn
* @return {?}
*/
Location.prototype.subscribe = function (onNext, onThrow, onReturn) {
return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });
};
/**
* Given a string of url parameters, prepend with '?' if needed, otherwise return parameters as
* is.
* @param {?} params
* @return {?}
*/
Location.normalizeQueryParams = function (params) {
return params && params[0] !== '?' ? '?' + params : params;
};
/**
* Given 2 parts of a url, join them with a slash if needed.
* @param {?} start
* @param {?} end
* @return {?}
*/
Location.joinWithSlash = function (start, end) {
if (start.length == 0) {
return end;
}
if (end.length == 0) {
return start;
}
var /** @type {?} */ slashes = 0;
if (start.endsWith('/')) {
slashes++;
}
if (end.startsWith('/')) {
slashes++;
}
if (slashes == 2) {
return start + end.substring(1);
}
if (slashes == 1) {
return start + end;
}
return start + '/' + end;
};
/**
* If url has a trailing slash, remove it, otherwise return url as is.
* @param {?} url
* @return {?}
*/
Location.stripTrailingSlash = function (url) { return url.replace(/\/$/, ''); };
return Location;
}());
Location.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
Location.ctorParameters = function () { return [
{ type: LocationStrategy, },
]; };
/**
* @param {?} baseHref
* @param {?} url
* @return {?}
*/
function _stripBaseHref(baseHref, url) {
return baseHref && url.startsWith(baseHref) ? url.substring(baseHref.length) : url;
}
/**
* @param {?} url
* @return {?}
*/
function _stripIndexHtml(url) {
return url.replace(/\/index.html$/, '');
}
/**
* @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
*/
/**
* \@whatItDoes Use URL hash for storing application location data.
* \@description
* `HashLocationStrategy` is a {\@link LocationStrategy} used to configure the
* {\@link Location} service to represent its state in the
* [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax)
* of the browser's URL.
*
* For instance, if you call `location.go('/foo')`, the browser's URL will become
* `example.com#/foo`.
*
* ### Example
*
* {\@example common/location/ts/hash_location_component.ts region='LocationComponent'}
*
* \@stable
*/
var HashLocationStrategy = (function (_super) {
__extends(HashLocationStrategy, _super);
/**
* @param {?} _platformLocation
* @param {?=} _baseHref
*/
function HashLocationStrategy(_platformLocation, _baseHref) {
var _this = _super.call(this) || this;
_this._platformLocation = _platformLocation;
_this._baseHref = '';
if (_baseHref != null) {
_this._baseHref = _baseHref;
}
return _this;
}
/**
* @param {?} fn
* @return {?}
*/
HashLocationStrategy.prototype.onPopState = function (fn) {
this._platformLocation.onPopState(fn);
this._platformLocation.onHashChange(fn);
};
/**
* @return {?}
*/
HashLocationStrategy.prototype.getBaseHref = function () { return this._baseHref; };
/**
* @param {?=} includeHash
* @return {?}
*/
HashLocationStrategy.prototype.path = function (includeHash) {
if (includeHash === void 0) { includeHash = false; }
// the hash value is always prefixed with a `#`
// and if it is empty then it will stay empty
var /** @type {?} */ path = this._platformLocation.hash;
if (path == null)
path = '#';
return path.length > 0 ? path.substring(1) : path;
};
/**
* @param {?} internal
* @return {?}
*/
HashLocationStrategy.prototype.prepareExternalUrl = function (internal) {
var /** @type {?} */ url = Location.joinWithSlash(this._baseHref, internal);
return url.length > 0 ? ('#' + url) : url;
};
/**
* @param {?} state
* @param {?} title
* @param {?} path
* @param {?} queryParams
* @return {?}
*/
HashLocationStrategy.prototype.pushState = function (state, title, path, queryParams) {
var /** @type {?} */ url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
if (url.length == 0) {
url = this._platformLocation.pathname;
}
this._platformLocation.pushState(state, title, url);
};
/**
* @param {?} state
* @param {?} title
* @param {?} path
* @param {?} queryParams
* @return {?}
*/
HashLocationStrategy.prototype.replaceState = function (state, title, path, queryParams) {
var /** @type {?} */ url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
if (url.length == 0) {
url = this._platformLocation.pathname;
}
this._platformLocation.replaceState(state, title, url);
};
/**
* @return {?}
*/
HashLocationStrategy.prototype.forward = function () { this._platformLocation.forward(); };
/**
* @return {?}
*/
HashLocationStrategy.prototype.back = function () { this._platformLocation.back(); };
return HashLocationStrategy;
}(LocationStrategy));
HashLocationStrategy.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
HashLocationStrategy.ctorParameters = function () { return [
{ type: PlatformLocation, },
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [APP_BASE_HREF,] },] },
]; };
/**
* @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
*/
/**
* \@whatItDoes Use URL for storing application location data.
* \@description
* `PathLocationStrategy` is a {\@link LocationStrategy} used to configure the
* {\@link Location} service to represent its state in the
* [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the
* browser's URL.
*
* If you're using `PathLocationStrategy`, you must provide a {\@link APP_BASE_HREF}
* or add a base element to the document. This URL prefix that will be preserved
* when generating and recognizing URLs.
*
* For instance, if you provide an `APP_BASE_HREF` of `'/my/app'` and call
* `location.go('/foo')`, the browser's URL will become
* `example.com/my/app/foo`.
*
* Similarly, if you add `<base href='/my/app'/>` to the document and call
* `location.go('/foo')`, the browser's URL will become
* `example.com/my/app/foo`.
*
* ### Example
*
* {\@example common/location/ts/path_location_component.ts region='LocationComponent'}
*
* \@stable
*/
var PathLocationStrategy = (function (_super) {
__extends(PathLocationStrategy, _super);
/**
* @param {?} _platformLocation
* @param {?=} href
*/
function PathLocationStrategy(_platformLocation, href) {
var _this = _super.call(this) || this;
_this._platformLocation = _platformLocation;
if (href == null) {
href = _this._platformLocation.getBaseHrefFromDOM();
}
if (href == null) {
throw new Error("No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.");
}
_this._baseHref = href;
return _this;
}
/**
* @param {?} fn
* @return {?}
*/
PathLocationStrategy.prototype.onPopState = function (fn) {
this._platformLocation.onPopState(fn);
this._platformLocation.onHashChange(fn);
};
/**
* @return {?}
*/
PathLocationStrategy.prototype.getBaseHref = function () { return this._baseHref; };
/**
* @param {?} internal
* @return {?}
*/
PathLocationStrategy.prototype.prepareExternalUrl = function (internal) {
return Location.joinWithSlash(this._baseHref, internal);
};
/**
* @param {?=} includeHash
* @return {?}
*/
PathLocationStrategy.prototype.path = function (includeHash) {
if (includeHash === void 0) { includeHash = false; }
var /** @type {?} */ pathname = this._platformLocation.pathname +
Location.normalizeQueryParams(this._platformLocation.search);
var /** @type {?} */ hash = this._platformLocation.hash;
return hash && includeHash ? "" + pathname + hash : pathname;
};
/**
* @param {?} state
* @param {?} title
* @param {?} url
* @param {?} queryParams
* @return {?}
*/
PathLocationStrategy.prototype.pushState = function (state, title, url, queryParams) {
var /** @type {?} */ externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams));
this._platformLocation.pushState(state, title, externalUrl);
};
/**
* @param {?} state
* @param {?} title
* @param {?} url
* @param {?} queryParams
* @return {?}
*/
PathLocationStrategy.prototype.replaceState = function (state, title, url, queryParams) {
var /** @type {?} */ externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams));
this._platformLocation.replaceState(state, title, externalUrl);
};
/**
* @return {?}
*/
PathLocationStrategy.prototype.forward = function () { this._platformLocation.forward(); };
/**
* @return {?}
*/
PathLocationStrategy.prototype.back = function () { this._platformLocation.back(); };
return PathLocationStrategy;
}(LocationStrategy));
PathLocationStrategy.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
PathLocationStrategy.ctorParameters = function () { return [
{ type: PlatformLocation, },
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [APP_BASE_HREF,] },] },
]; };
/**
* @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
*/
/**
* @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
*/
/**
* \@experimental
* @abstract
*/
var NgLocalization = (function () {
function NgLocalization() {
}
/**
* @abstract
* @param {?} value
* @return {?}
*/
NgLocalization.prototype.getPluralCategory = function (value) { };
return NgLocalization;
}());
/**
* Returns the plural category for a given value.
* - "=value" when the case exists,
* - the plural category otherwise
*
* \@internal
* @param {?} value
* @param {?} cases
* @param {?} ngLocalization
* @return {?}
*/
function getPluralCategory(value, cases, ngLocalization) {
var /** @type {?} */ key = "=" + value;
if (cases.indexOf(key) > -1) {
return key;
}
key = ngLocalization.getPluralCategory(value);
if (cases.indexOf(key) > -1) {
return key;
}
if (cases.indexOf('other') > -1) {
return 'other';
}
throw new Error("No plural message found for value \"" + value + "\"");
}
/**
* Returns the plural case based on the locale
*
* \@experimental
*/
var NgLocaleLocalization = (function (_super) {
__extends(NgLocaleLocalization, _super);
/**
* @param {?} locale
*/
function NgLocaleLocalization(locale) {
var _this = _super.call(this) || this;
_this.locale = locale;
return _this;
}
/**
* @param {?} value
* @return {?}
*/
NgLocaleLocalization.prototype.getPluralCategory = function (value) {
var /** @type {?} */ plural = getPluralCase(this.locale, value);
switch (plural) {
case Plural.Zero:
return 'zero';
case Plural.One:
return 'one';
case Plural.Two:
return 'two';
case Plural.Few:
return 'few';
case Plural.Many:
return 'many';
default:
return 'other';
}
};
return NgLocaleLocalization;
}(NgLocalization));
NgLocaleLocalization.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
NgLocaleLocalization.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [__WEBPACK_IMPORTED_MODULE_0__angular_core__["Q" /* LOCALE_ID */],] },] },
]; };
var Plural = {};
Plural.Zero = 0;
Plural.One = 1;
Plural.Two = 2;
Plural.Few = 3;
Plural.Many = 4;
Plural.Other = 5;
Plural[Plural.Zero] = "Zero";
Plural[Plural.One] = "One";
Plural[Plural.Two] = "Two";
Plural[Plural.Few] = "Few";
Plural[Plural.Many] = "Many";
Plural[Plural.Other] = "Other";
/**
* Returns the plural case based on the locale
*
* \@experimental
* @param {?} locale
* @param {?} nLike
* @return {?}
*/
function getPluralCase(locale, nLike) {
// TODO(vicb): lazy compute
if (typeof nLike === 'string') {
nLike = parseInt(/** @type {?} */ (nLike), 10);
}
var /** @type {?} */ n = (nLike);
var /** @type {?} */ nDecimal = n.toString().replace(/^[^.]*\.?/, '');
var /** @type {?} */ i = Math.floor(Math.abs(n));
var /** @type {?} */ v = nDecimal.length;
var /** @type {?} */ f = parseInt(nDecimal, 10);
var /** @type {?} */ t = parseInt(n.toString().replace(/^[^.]*\.?|0+$/g, ''), 10) || 0;
var /** @type {?} */ lang = locale.split('-')[0].toLowerCase();
switch (lang) {
case 'af':
case 'asa':
case 'az':
case 'bem':
case 'bez':
case 'bg':
case 'brx':
case 'ce':
case 'cgg':
case 'chr':
case 'ckb':
case 'ee':
case 'el':
case 'eo':
case 'es':
case 'eu':
case 'fo':
case 'fur':
case 'gsw':
case 'ha':
case 'haw':
case 'hu':
case 'jgo':
case 'jmc':
case 'ka':
case 'kk':
case 'kkj':
case 'kl':
case 'ks':
case 'ksb':
case 'ky':
case 'lb':
case 'lg':
case 'mas':
case 'mgo':
case 'ml':
case 'mn':
case 'nb':
case 'nd':
case 'ne':
case 'nn':
case 'nnh':
case 'nyn':
case 'om':
case 'or':
case 'os':
case 'ps':
case 'rm':
case 'rof':
case 'rwk':
case 'saq':
case 'seh':
case 'sn':
case 'so':
case 'sq':
case 'ta':
case 'te':
case 'teo':
case 'tk':
case 'tr':
case 'ug':
case 'uz':
case 'vo':
case 'vun':
case 'wae':
case 'xog':
if (n === 1)
return Plural.One;
return Plural.Other;
case 'agq':
case 'bas':
case 'cu':
case 'dav':
case 'dje':
case 'dua':
case 'dyo':
case 'ebu':
case 'ewo':
case 'guz':
case 'kam':
case 'khq':
case 'ki':
case 'kln':
case 'kok':
case 'ksf':
case 'lrc':
case 'lu':
case 'luo':
case 'luy':
case 'mer':
case 'mfe':
case 'mgh':
case 'mua':
case 'mzn':
case 'nmg':
case 'nus':
case 'qu':
case 'rn':
case 'rw':
case 'sbp':
case 'twq':
case 'vai':
case 'yav':
case 'yue':
case 'zgh':
case 'ak':
case 'ln':
case 'mg':
case 'pa':
case 'ti':
if (n === Math.floor(n) && n >= 0 && n <= 1)
return Plural.One;
return Plural.Other;
case 'am':
case 'as':
case 'bn':
case 'fa':
case 'gu':
case 'hi':
case 'kn':
case 'mr':
case 'zu':
if (i === 0 || n === 1)
return Plural.One;
return Plural.Other;
case 'ar':
if (n === 0)
return Plural.Zero;
if (n === 1)
return Plural.One;
if (n === 2)
return Plural.Two;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10)
return Plural.Few;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99)
return Plural.Many;
return Plural.Other;
case 'ast':
case 'ca':
case 'de':
case 'en':
case 'et':
case 'fi':
case 'fy':
case 'gl':
case 'it':
case 'nl':
case 'sv':
case 'sw':
case 'ur':
case 'yi':
if (i === 1 && v === 0)
return Plural.One;
return Plural.Other;
case 'be':
if (n % 10 === 1 && !(n % 100 === 11))
return Plural.One;
if (n % 10 === Math.floor(n % 10) && n % 10 >= 2 && n % 10 <= 4 &&
!(n % 100 >= 12 && n % 100 <= 14))
return Plural.Few;
if (n % 10 === 0 || n % 10 === Math.floor(n % 10) && n % 10 >= 5 && n % 10 <= 9 ||
n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 14)
return Plural.Many;
return Plural.Other;
case 'br':
if (n % 10 === 1 && !(n % 100 === 11 || n % 100 === 71 || n % 100 === 91))
return Plural.One;
if (n % 10 === 2 && !(n % 100 === 12 || n % 100 === 72 || n % 100 === 92))
return Plural.Two;
if (n % 10 === Math.floor(n % 10) && (n % 10 >= 3 && n % 10 <= 4 || n % 10 === 9) &&
!(n % 100 >= 10 && n % 100 <= 19 || n % 100 >= 70 && n % 100 <= 79 ||
n % 100 >= 90 && n % 100 <= 99))
return Plural.Few;
if (!(n === 0) && n % 1e6 === 0)
return Plural.Many;
return Plural.Other;
case 'bs':
case 'hr':
case 'sr':
if (v === 0 && i % 10 === 1 && !(i % 100 === 11) || f % 10 === 1 && !(f % 100 === 11))
return Plural.One;
if (v === 0 && i % 10 === Math.floor(i % 10) && i % 10 >= 2 && i % 10 <= 4 &&
!(i % 100 >= 12 && i % 100 <= 14) ||
f % 10 === Math.floor(f % 10) && f % 10 >= 2 && f % 10 <= 4 &&
!(f % 100 >= 12 && f % 100 <= 14))
return Plural.Few;
return Plural.Other;
case 'cs':
case 'sk':
if (i === 1 && v === 0)
return Plural.One;
if (i === Math.floor(i) && i >= 2 && i <= 4 && v === 0)
return Plural.Few;
if (!(v === 0))
return Plural.Many;
return Plural.Other;
case 'cy':
if (n === 0)
return Plural.Zero;
if (n === 1)
return Plural.One;
if (n === 2)
return Plural.Two;
if (n === 3)
return Plural.Few;
if (n === 6)
return Plural.Many;
return Plural.Other;
case 'da':
if (n === 1 || !(t === 0) && (i === 0 || i === 1))
return Plural.One;
return Plural.Other;
case 'dsb':
case 'hsb':
if (v === 0 && i % 100 === 1 || f % 100 === 1)
return Plural.One;
if (v === 0 && i % 100 === 2 || f % 100 === 2)
return Plural.Two;
if (v === 0 && i % 100 === Math.floor(i % 100) && i % 100 >= 3 && i % 100 <= 4 ||
f % 100 === Math.floor(f % 100) && f % 100 >= 3 && f % 100 <= 4)
return Plural.Few;
return Plural.Other;
case 'ff':
case 'fr':
case 'hy':
case 'kab':
if (i === 0 || i === 1)
return Plural.One;
return Plural.Other;
case 'fil':
if (v === 0 && (i === 1 || i === 2 || i === 3) ||
v === 0 && !(i % 10 === 4 || i % 10 === 6 || i % 10 === 9) ||
!(v === 0) && !(f % 10 === 4 || f % 10 === 6 || f % 10 === 9))
return Plural.One;
return Plural.Other;
case 'ga':
if (n === 1)
return Plural.One;
if (n === 2)
return Plural.Two;
if (n === Math.floor(n) && n >= 3 && n <= 6)
return Plural.Few;
if (n === Math.floor(n) && n >= 7 && n <= 10)
return Plural.Many;
return Plural.Other;
case 'gd':
if (n === 1 || n === 11)
return Plural.One;
if (n === 2 || n === 12)
return Plural.Two;
if (n === Math.floor(n) && (n >= 3 && n <= 10 || n >= 13 && n <= 19))
return Plural.Few;
return Plural.Other;
case 'gv':
if (v === 0 && i % 10 === 1)
return Plural.One;
if (v === 0 && i % 10 === 2)
return Plural.Two;
if (v === 0 &&
(i % 100 === 0 || i % 100 === 20 || i % 100 === 40 || i % 100 === 60 || i % 100 === 80))
return Plural.Few;
if (!(v === 0))
return Plural.Many;
return Plural.Other;
case 'he':
if (i === 1 && v === 0)
return Plural.One;
if (i === 2 && v === 0)
return Plural.Two;
if (v === 0 && !(n >= 0 && n <= 10) && n % 10 === 0)
return Plural.Many;
return Plural.Other;
case 'is':
if (t === 0 && i % 10 === 1 && !(i % 100 === 11) || !(t === 0))
return Plural.One;
return Plural.Other;
case 'ksh':
if (n === 0)
return Plural.Zero;
if (n === 1)
return Plural.One;
return Plural.Other;
case 'kw':
case 'naq':
case 'se':
case 'smn':
if (n === 1)
return Plural.One;
if (n === 2)
return Plural.Two;
return Plural.Other;
case 'lag':
if (n === 0)
return Plural.Zero;
if ((i === 0 || i === 1) && !(n === 0))
return Plural.One;
return Plural.Other;
case 'lt':
if (n % 10 === 1 && !(n % 100 >= 11 && n % 100 <= 19))
return Plural.One;
if (n % 10 === Math.floor(n % 10) && n % 10 >= 2 && n % 10 <= 9 &&
!(n % 100 >= 11 && n % 100 <= 19))
return Plural.Few;
if (!(f === 0))
return Plural.Many;
return Plural.Other;
case 'lv':
case 'prg':
if (n % 10 === 0 || n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 19 ||
v === 2 && f % 100 === Math.floor(f % 100) && f % 100 >= 11 && f % 100 <= 19)
return Plural.Zero;
if (n % 10 === 1 && !(n % 100 === 11) || v === 2 && f % 10 === 1 && !(f % 100 === 11) ||
!(v === 2) && f % 10 === 1)
return Plural.One;
return Plural.Other;
case 'mk':
if (v === 0 && i % 10 === 1 || f % 10 === 1)
return Plural.One;
return Plural.Other;
case 'mt':
if (n === 1)
return Plural.One;
if (n === 0 || n % 100 === Math.floor(n % 100) && n % 100 >= 2 && n % 100 <= 10)
return Plural.Few;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 19)
return Plural.Many;
return Plural.Other;
case 'pl':
if (i === 1 && v === 0)
return Plural.One;
if (v === 0 && i % 10 === Math.floor(i % 10) && i % 10 >= 2 && i % 10 <= 4 &&
!(i % 100 >= 12 && i % 100 <= 14))
return Plural.Few;
if (v === 0 && !(i === 1) && i % 10 === Math.floor(i % 10) && i % 10 >= 0 && i % 10 <= 1 ||
v === 0 && i % 10 === Math.floor(i % 10) && i % 10 >= 5 && i % 10 <= 9 ||
v === 0 && i % 100 === Math.floor(i % 100) && i % 100 >= 12 && i % 100 <= 14)
return Plural.Many;
return Plural.Other;
case 'pt':
if (n === Math.floor(n) && n >= 0 && n <= 2 && !(n === 2))
return Plural.One;
return Plural.Other;
case 'ro':
if (i === 1 && v === 0)
return Plural.One;
if (!(v === 0) || n === 0 ||
!(n === 1) && n % 100 === Math.floor(n % 100) && n % 100 >= 1 && n % 100 <= 19)
return Plural.Few;
return Plural.Other;
case 'ru':
case 'uk':
if (v === 0 && i % 10 === 1 && !(i % 100 === 11))
return Plural.One;
if (v === 0 && i % 10 === Math.floor(i % 10) && i % 10 >= 2 && i % 10 <= 4 &&
!(i % 100 >= 12 && i % 100 <= 14))
return Plural.Few;
if (v === 0 && i % 10 === 0 ||
v === 0 && i % 10 === Math.floor(i % 10) && i % 10 >= 5 && i % 10 <= 9 ||
v === 0 && i % 100 === Math.floor(i % 100) && i % 100 >= 11 && i % 100 <= 14)
return Plural.Many;
return Plural.Other;
case 'shi':
if (i === 0 || n === 1)
return Plural.One;
if (n === Math.floor(n) && n >= 2 && n <= 10)
return Plural.Few;
return Plural.Other;
case 'si':
if (n === 0 || n === 1 || i === 0 && f === 1)
return Plural.One;
return Plural.Other;
case 'sl':
if (v === 0 && i % 100 === 1)
return Plural.One;
if (v === 0 && i % 100 === 2)
return Plural.Two;
if (v === 0 && i % 100 === Math.floor(i % 100) && i % 100 >= 3 && i % 100 <= 4 || !(v === 0))
return Plural.Few;
return Plural.Other;
case 'tzm':
if (n === Math.floor(n) && n >= 0 && n <= 1 || n === Math.floor(n) && n >= 11 && n <= 99)
return Plural.One;
return Plural.Other;
default:
return Plural.Other;
}
}
/**
* @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
*/
/**
* \@ngModule CommonModule
*
* \@whatItDoes Adds and removes CSS classes on an HTML element.
*
* \@howToUse
* ```
* <some-element [ngClass]="'first second'">...</some-element>
*
* <some-element [ngClass]="['first', 'second']">...</some-element>
*
* <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
*
* <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
*
* <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
* ```
*
* \@description
*
* The CSS classes are updated as follows, depending on the type of the expression evaluation:
* - `string` - the CSS classes listed in the string (space delimited) are added,
* - `Array` - the CSS classes declared as Array elements are added,
* - `Object` - keys are CSS classes that get added when the expression given in the value
* evaluates to a truthy value, otherwise they are removed.
*
* \@stable
*/
var NgClass = (function () {
/**
* @param {?} _iterableDiffers
* @param {?} _keyValueDiffers
* @param {?} _ngEl
* @param {?} _renderer
*/
function NgClass(_iterableDiffers, _keyValueDiffers, _ngEl, _renderer) {
this._iterableDiffers = _iterableDiffers;
this._keyValueDiffers = _keyValueDiffers;
this._ngEl = _ngEl;
this._renderer = _renderer;
this._initialClasses = [];
}
Object.defineProperty(NgClass.prototype, "klass", {
/**
* @param {?} v
* @return {?}
*/
set: function (v) {
this._applyInitialClasses(true);
this._initialClasses = typeof v === 'string' ? v.split(/\s+/) : [];
this._applyInitialClasses(false);
this._applyClasses(this._rawClass, false);
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgClass.prototype, "ngClass", {
/**
* @param {?} v
* @return {?}
*/
set: function (v) {
this._cleanupClasses(this._rawClass);
this._iterableDiffer = null;
this._keyValueDiffer = null;
this._rawClass = typeof v === 'string' ? v.split(/\s+/) : v;
if (this._rawClass) {
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["R" /* ɵisListLikeIterable */])(this._rawClass)) {
this._iterableDiffer = this._iterableDiffers.find(this._rawClass).create();
}
else {
this._keyValueDiffer = this._keyValueDiffers.find(this._rawClass).create();
}
}
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
NgClass.prototype.ngDoCheck = function () {
if (this._iterableDiffer) {
var /** @type {?} */ iterableChanges = this._iterableDiffer.diff(/** @type {?} */ (this._rawClass));
if (iterableChanges) {
this._applyIterableChanges(iterableChanges);
}
}
else if (this._keyValueDiffer) {
var /** @type {?} */ keyValueChanges = this._keyValueDiffer.diff(/** @type {?} */ (this._rawClass));
if (keyValueChanges) {
this._applyKeyValueChanges(keyValueChanges);
}
}
};
/**
* @param {?} rawClassVal
* @return {?}
*/
NgClass.prototype._cleanupClasses = function (rawClassVal) {
this._applyClasses(rawClassVal, true);
this._applyInitialClasses(false);
};
/**
* @param {?} changes
* @return {?}
*/
NgClass.prototype._applyKeyValueChanges = function (changes) {
var _this = this;
changes.forEachAddedItem(function (record) { return _this._toggleClass(record.key, record.currentValue); });
changes.forEachChangedItem(function (record) { return _this._toggleClass(record.key, record.currentValue); });
changes.forEachRemovedItem(function (record) {
if (record.previousValue) {
_this._toggleClass(record.key, false);
}
});
};
/**
* @param {?} changes
* @return {?}
*/
NgClass.prototype._applyIterableChanges = function (changes) {
var _this = this;
changes.forEachAddedItem(function (record) {
if (typeof record.item === 'string') {
_this._toggleClass(record.item, true);
}
else {
throw new Error("NgClass can only toggle CSS classes expressed as strings, got " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(record.item));
}
});
changes.forEachRemovedItem(function (record) { return _this._toggleClass(record.item, false); });
};
/**
* @param {?} isCleanup
* @return {?}
*/
NgClass.prototype._applyInitialClasses = function (isCleanup) {
var _this = this;
this._initialClasses.forEach(function (klass) { return _this._toggleClass(klass, !isCleanup); });
};
/**
* @param {?} rawClassVal
* @param {?} isCleanup
* @return {?}
*/
NgClass.prototype._applyClasses = function (rawClassVal, isCleanup) {
var _this = this;
if (rawClassVal) {
if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) {
((rawClassVal)).forEach(function (klass) { return _this._toggleClass(klass, !isCleanup); });
}
else {
Object.keys(rawClassVal).forEach(function (klass) {
if (rawClassVal[klass] != null)
_this._toggleClass(klass, !isCleanup);
});
}
}
};
/**
* @param {?} klass
* @param {?} enabled
* @return {?}
*/
NgClass.prototype._toggleClass = function (klass, enabled) {
var _this = this;
klass = klass.trim();
if (klass) {
klass.split(/\s+/g).forEach(function (klass) { _this._renderer.setElementClass(_this._ngEl.nativeElement, klass, !!enabled); });
}
};
return NgClass;
}());
NgClass.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngClass]' },] },
];
/**
* @nocollapse
*/
NgClass.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["T" /* IterableDiffers */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["U" /* KeyValueDiffers */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
]; };
NgClass.propDecorators = {
'klass': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */], args: ['class',] },],
'ngClass': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* @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
*/
/**
* Instantiates a single {\@link Component} type and inserts its Host View into current View.
* `NgComponentOutlet` provides a declarative approach for dynamic component creation.
*
* `NgComponentOutlet` requires a component type, if a falsy value is set the view will clear and
* any existing component will get destroyed.
*
* ### Fine tune control
*
* You can control the component creation process by using the following optional attributes:
*
* * `ngComponentOutletInjector`: Optional custom {\@link Injector} that will be used as parent for
* the Component. Defaults to the injector of the current view container.
*
* * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content
* section of the component, if exists.
*
* * `ngComponentOutletNgModuleFactory`: Optional module factory to allow dynamically loading other
* module, then load a component from that module.
*
* ### Syntax
*
* Simple
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container>
* ```
*
* Customized injector/content
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
* injector: injectorExpression;
* content: contentNodesExpression;">
* </ng-container>
* ```
*
* Customized ngModuleFactory
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
* ngModuleFactory: moduleFactory;">
* </ng-container>
* ```
* # Example
*
* {\@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'}
*
* A more complete example with additional options:
*
* {\@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'}
* A more complete example with ngModuleFactory:
*
* {\@example common/ngComponentOutlet/ts/module.ts region='NgModuleFactoryExample'}
*
* \@experimental
*/
var NgComponentOutlet = (function () {
/**
* @param {?} _viewContainerRef
*/
function NgComponentOutlet(_viewContainerRef) {
this._viewContainerRef = _viewContainerRef;
this._componentRef = null;
this._moduleRef = null;
}
/**
* @param {?} changes
* @return {?}
*/
NgComponentOutlet.prototype.ngOnChanges = function (changes) {
this._viewContainerRef.clear();
this._componentRef = null;
if (this.ngComponentOutlet) {
var /** @type {?} */ elInjector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector;
if (changes['ngComponentOutletNgModuleFactory']) {
if (this._moduleRef)
this._moduleRef.destroy();
if (this.ngComponentOutletNgModuleFactory) {
var /** @type {?} */ parentModule = elInjector.get(__WEBPACK_IMPORTED_MODULE_0__angular_core__["V" /* NgModuleRef */]);
this._moduleRef = this.ngComponentOutletNgModuleFactory.create(parentModule.injector);
}
else {
this._moduleRef = null;
}
}
var /** @type {?} */ componentFactoryResolver = this._moduleRef ? this._moduleRef.componentFactoryResolver :
elInjector.get(__WEBPACK_IMPORTED_MODULE_0__angular_core__["W" /* ComponentFactoryResolver */]);
var /** @type {?} */ componentFactory = componentFactoryResolver.resolveComponentFactory(this.ngComponentOutlet);
this._componentRef = this._viewContainerRef.createComponent(componentFactory, this._viewContainerRef.length, elInjector, this.ngComponentOutletContent);
}
};
/**
* @return {?}
*/
NgComponentOutlet.prototype.ngOnDestroy = function () {
if (this._moduleRef)
this._moduleRef.destroy();
};
return NgComponentOutlet;
}());
NgComponentOutlet.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngComponentOutlet]' },] },
];
/**
* @nocollapse
*/
NgComponentOutlet.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["X" /* ViewContainerRef */], },
]; };
NgComponentOutlet.propDecorators = {
'ngComponentOutlet': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngComponentOutletInjector': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngComponentOutletContent': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngComponentOutletNgModuleFactory': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* @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
*/
/**
* \@stable
*/
var NgForOfContext = (function () {
/**
* @param {?} $implicit
* @param {?} ngForOf
* @param {?} index
* @param {?} count
*/
function NgForOfContext($implicit, ngForOf, index, count) {
this.$implicit = $implicit;
this.ngForOf = ngForOf;
this.index = index;
this.count = count;
}
Object.defineProperty(NgForOfContext.prototype, "first", {
/**
* @return {?}
*/
get: function () { return this.index === 0; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForOfContext.prototype, "last", {
/**
* @return {?}
*/
get: function () { return this.index === this.count - 1; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForOfContext.prototype, "even", {
/**
* @return {?}
*/
get: function () { return this.index % 2 === 0; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForOfContext.prototype, "odd", {
/**
* @return {?}
*/
get: function () { return !this.even; },
enumerable: true,
configurable: true
});
return NgForOfContext;
}());
/**
* The `NgForOf` directive instantiates a template once per item from an iterable. The context
* for each instantiated template inherits from the outer context with the given loop variable
* set to the current item from the iterable.
*
* ### Local Variables
*
* `NgForOf` provides several exported values that can be aliased to local variables:
*
* - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`).
* - `ngForOf: NgIterable<T>`: The value of the iterable expression. Useful when the expression is
* more complex then a property access, for example when using the async pipe (`userStreams |
* async`).
* - `index: number`: The index of the current item in the iterable.
* - `first: boolean`: True when the item is the first item in the iterable.
* - `last: boolean`: True when the item is the last item in the iterable.
* - `even: boolean`: True when the item has an even index in the iterable.
* - `odd: boolean`: True when the item has an odd index in the iterable.
*
* ```
* <li *ngFor="let user of userObservable | async as users; index as i; first as isFirst">
* {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span>
* </li>
* ```
*
* ### Change Propagation
*
* When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
* * Otherwise, the DOM element for that item will remain the same.
*
* Angular uses object identity to track insertions and deletions within the iterator and reproduce
* those changes in the DOM. This has important implications for animations and any stateful
* controls (such as `<input>` elements which accept user input) that are present. Inserted rows can
* be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state
* such as user input.
*
* It is possible for the identities of elements in the iterator to change while the data does not.
* This can happen, for example, if the iterator produced from an RPC to the server, and that
* RPC is re-run. Even if the data hasn't changed, the second response will produce objects with
* different identities, and Angular will tear down the entire DOM and rebuild it (as if all old
* elements were deleted and all new elements inserted). This is an expensive operation and should
* be avoided if possible.
*
* To customize the default tracking algorithm, `NgForOf` supports `trackBy` option.
* `trackBy` takes a function which has two arguments: `index` and `item`.
* If `trackBy` is given, Angular tracks changes by the return value of the function.
*
* ### Syntax
*
* - `<li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>`
* - `<li template="ngFor let item of items; index as i; trackBy: trackByFn">...</li>`
*
* With `<ng-template>` element:
*
* ```
* <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
* <li>...</li>
* </ng-template>
* ```
*
* ### Example
*
* See a [live demo](http://plnkr.co/edit/KVuXxDp0qinGDyo307QW?p=preview) for a more detailed
* example.
*
* \@stable
*/
var NgForOf = (function () {
/**
* @param {?} _viewContainer
* @param {?} _template
* @param {?} _differs
*/
function NgForOf(_viewContainer, _template, _differs) {
this._viewContainer = _viewContainer;
this._template = _template;
this._differs = _differs;
this._differ = null;
}
Object.defineProperty(NgForOf.prototype, "ngForTrackBy", {
/**
* @return {?}
*/
get: function () { return this._trackByFn; },
/**
* @param {?} fn
* @return {?}
*/
set: function (fn) {
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["E" /* isDevMode */])() && fn != null && typeof fn !== 'function') {
// TODO(vicb): use a log service once there is a public one available
if ((console) && (console.warn)) {
console.warn("trackBy must be a function, but received " + JSON.stringify(fn) + ". " +
"See https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html#!#change-propagation for more information.");
}
}
this._trackByFn = fn;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgForOf.prototype, "ngForTemplate", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
// TODO(TS2.1): make TemplateRef<Partial<NgForRowOf<T>>> once we move to TS v2.1
// The current type is too restrictive; a template that just uses index, for example,
// should be acceptable.
if (value) {
this._template = value;
}
},
enumerable: true,
configurable: true
});
/**
* @param {?} changes
* @return {?}
*/
NgForOf.prototype.ngOnChanges = function (changes) {
if ('ngForOf' in changes) {
// React on ngForOf changes only once all inputs have been initialized
var /** @type {?} */ value = changes['ngForOf'].currentValue;
if (!this._differ && value) {
try {
this._differ = this._differs.find(value).create(this.ngForTrackBy);
}
catch (e) {
throw new Error("Cannot find a differ supporting object '" + value + "' of type '" + getTypeNameForDebugging(value) + "'. NgFor only supports binding to Iterables such as Arrays.");
}
}
}
};
/**
* @return {?}
*/
NgForOf.prototype.ngDoCheck = function () {
if (this._differ) {
var /** @type {?} */ changes = this._differ.diff(this.ngForOf);
if (changes)
this._applyChanges(changes);
}
};
/**
* @param {?} changes
* @return {?}
*/
NgForOf.prototype._applyChanges = function (changes) {
var _this = this;
var /** @type {?} */ insertTuples = [];
changes.forEachOperation(function (item, adjustedPreviousIndex, currentIndex) {
if (item.previousIndex == null) {
var /** @type {?} */ view = _this._viewContainer.createEmbeddedView(_this._template, new NgForOfContext(/** @type {?} */ ((null)), _this.ngForOf, -1, -1), currentIndex);
var /** @type {?} */ tuple = new RecordViewTuple(item, view);
insertTuples.push(tuple);
}
else if (currentIndex == null) {
_this._viewContainer.remove(adjustedPreviousIndex);
}
else {
var /** @type {?} */ view = ((_this._viewContainer.get(adjustedPreviousIndex)));
_this._viewContainer.move(view, currentIndex);
var /** @type {?} */ tuple = new RecordViewTuple(item, /** @type {?} */ (view));
insertTuples.push(tuple);
}
});
for (var /** @type {?} */ i = 0; i < insertTuples.length; i++) {
this._perViewChange(insertTuples[i].view, insertTuples[i].record);
}
for (var /** @type {?} */ i = 0, /** @type {?} */ ilen = this._viewContainer.length; i < ilen; i++) {
var /** @type {?} */ viewRef = (this._viewContainer.get(i));
viewRef.context.index = i;
viewRef.context.count = ilen;
}
changes.forEachIdentityChange(function (record) {
var /** @type {?} */ viewRef = (_this._viewContainer.get(record.currentIndex));
viewRef.context.$implicit = record.item;
});
};
/**
* @param {?} view
* @param {?} record
* @return {?}
*/
NgForOf.prototype._perViewChange = function (view, record) {
view.context.$implicit = record.item;
};
return NgForOf;
}());
NgForOf.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngFor][ngForOf]' },] },
];
/**
* @nocollapse
*/
NgForOf.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["X" /* ViewContainerRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["Y" /* TemplateRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["T" /* IterableDiffers */], },
]; };
NgForOf.propDecorators = {
'ngForOf': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngForTrackBy': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngForTemplate': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
var RecordViewTuple = (function () {
/**
* @param {?} record
* @param {?} view
*/
function RecordViewTuple(record, view) {
this.record = record;
this.view = view;
}
return RecordViewTuple;
}());
/**
* @deprecated from v4.0.0 - Use NgForOf instead.
*/
var NgFor = NgForOf;
/**
* @param {?} type
* @return {?}
*/
function getTypeNameForDebugging(type) {
return type['name'] || typeof type;
}
/**
* @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
*/
/**
* Conditionally includes a template based on the value of an `expression`.
*
* `ngIf` evaluates the `expression` and then renders the `then` or `else` template in its place
* when expression is truthy or falsy respectively. Typically the:
* - `then` template is the inline template of `ngIf` unless bound to a different value.
* - `else` template is blank unless it is bound.
*
* # Most common usage
*
* The most common usage of the `ngIf` directive is to conditionally show the inline template as
* seen in this example:
* {\@example common/ngIf/ts/module.ts region='NgIfSimple'}
*
* # Showing an alternative template using `else`
*
* If it is necessary to display a template when the `expression` is falsy use the `else` template
* binding as shown. Note that the `else` binding points to a `<ng-template>` labeled `#elseBlock`.
* The template can be defined anywhere in the component view but is typically placed right after
* `ngIf` for readability.
*
* {\@example common/ngIf/ts/module.ts region='NgIfElse'}
*
* # Using non-inlined `then` template
*
* Usually the `then` template is the inlined template of the `ngIf`, but it can be changed using
* a binding (just like `else`). Because `then` and `else` are bindings, the template references can
* change at runtime as shown in this example.
*
* {\@example common/ngIf/ts/module.ts region='NgIfThenElse'}
*
* # Storing conditional result in a variable
*
* A common pattern is that we need to show a set of properties from the same object. If the
* object is undefined, then we have to use the safe-traversal-operator `?.` to guard against
* dereferencing a `null` value. This is especially the case when waiting on async data such as
* when using the `async` pipe as shown in folowing example:
*
* ```
* Hello {{ (userStream|async)?.last }}, {{ (userStream|async)?.first }}!
* ```
*
* There are several inefficiencies in the above example:
* - We create multiple subscriptions on `userStream`. One for each `async` pipe, or two in the
* example above.
* - We cannot display an alternative screen while waiting for the data to arrive asynchronously.
* - We have to use the safe-traversal-operator `?.` to access properties, which is cumbersome.
* - We have to place the `async` pipe in parenthesis.
*
* A better way to do this is to use `ngIf` and store the result of the condition in a local
* variable as shown in the the example below:
*
* {\@example common/ngIf/ts/module.ts region='NgIfAs'}
*
* Notice that:
* - We use only one `async` pipe and hence only one subscription gets created.
* - `ngIf` stores the result of the `userStream|async` in the local variable `user`.
* - The local `user` can then be bound repeatedly in a more efficient way.
* - No need to use the safe-traversal-operator `?.` to access properties as `ngIf` will only
* display the data if `userStream` returns a value.
* - We can display an alternative template while waiting for the data.
*
* ### Syntax
*
* Simple form:
* - `<div *ngIf="condition">...</div>`
* - `<div template="ngIf condition">...</div>`
* - `<ng-template [ngIf]="condition"><div>...</div></ng-template>`
*
* Form with an else block:
* ```
* <div *ngIf="condition; else elseBlock">...</div>
* <ng-template #elseBlock>...</ng-template>
* ```
*
* Form with a `then` and `else` block:
* ```
* <div *ngIf="condition; then thenBlock else elseBlock"></div>
* <ng-template #thenBlock>...</ng-template>
* <ng-template #elseBlock>...</ng-template>
* ```
*
* Form with storing the value locally:
* ```
* <div *ngIf="condition as value; else elseBlock">{{value}}</div>
* <ng-template #elseBlock>...</ng-template>
* ```
*
* \@stable
*/
var NgIf = (function () {
/**
* @param {?} _viewContainer
* @param {?} templateRef
*/
function NgIf(_viewContainer, templateRef) {
this._viewContainer = _viewContainer;
this._context = new NgIfContext();
this._thenTemplateRef = null;
this._elseTemplateRef = null;
this._thenViewRef = null;
this._elseViewRef = null;
this._thenTemplateRef = templateRef;
}
Object.defineProperty(NgIf.prototype, "ngIf", {
/**
* @param {?} condition
* @return {?}
*/
set: function (condition) {
this._context.$implicit = this._context.ngIf = condition;
this._updateView();
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgIf.prototype, "ngIfThen", {
/**
* @param {?} templateRef
* @return {?}
*/
set: function (templateRef) {
this._thenTemplateRef = templateRef;
this._thenViewRef = null; // clear previous view if any.
this._updateView();
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgIf.prototype, "ngIfElse", {
/**
* @param {?} templateRef
* @return {?}
*/
set: function (templateRef) {
this._elseTemplateRef = templateRef;
this._elseViewRef = null; // clear previous view if any.
this._updateView();
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
NgIf.prototype._updateView = function () {
if (this._context.$implicit) {
if (!this._thenViewRef) {
this._viewContainer.clear();
this._elseViewRef = null;
if (this._thenTemplateRef) {
this._thenViewRef =
this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
}
}
}
else {
if (!this._elseViewRef) {
this._viewContainer.clear();
this._thenViewRef = null;
if (this._elseTemplateRef) {
this._elseViewRef =
this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
}
}
}
};
return NgIf;
}());
NgIf.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngIf]' },] },
];
/**
* @nocollapse
*/
NgIf.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["X" /* ViewContainerRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["Y" /* TemplateRef */], },
]; };
NgIf.propDecorators = {
'ngIf': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngIfThen': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngIfElse': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* \@stable
*/
var NgIfContext = (function () {
function NgIfContext() {
this.$implicit = null;
this.ngIf = null;
}
return NgIfContext;
}());
/**
* @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
*/
var SwitchView = (function () {
/**
* @param {?} _viewContainerRef
* @param {?} _templateRef
*/
function SwitchView(_viewContainerRef, _templateRef) {
this._viewContainerRef = _viewContainerRef;
this._templateRef = _templateRef;
this._created = false;
}
/**
* @return {?}
*/
SwitchView.prototype.create = function () {
this._created = true;
this._viewContainerRef.createEmbeddedView(this._templateRef);
};
/**
* @return {?}
*/
SwitchView.prototype.destroy = function () {
this._created = false;
this._viewContainerRef.clear();
};
/**
* @param {?} created
* @return {?}
*/
SwitchView.prototype.enforceState = function (created) {
if (created && !this._created) {
this.create();
}
else if (!created && this._created) {
this.destroy();
}
};
return SwitchView;
}());
/**
* \@ngModule CommonModule
*
* \@whatItDoes Adds / removes DOM sub-trees when the nest match expressions matches the switch
* expression.
*
* \@howToUse
* ```
* <container-element [ngSwitch]="switch_expression">
* <some-element *ngSwitchCase="match_expression_1">...</some-element>
* <some-element *ngSwitchCase="match_expression_2">...</some-element>
* <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
* <ng-container *ngSwitchCase="match_expression_3">
* <!-- use a ng-container to group multiple root nodes -->
* <inner-element></inner-element>
* <inner-other-element></inner-other-element>
* </ng-container>
* <some-element *ngSwitchDefault>...</some-element>
* </container-element>
* ```
* \@description
*
* `NgSwitch` stamps out nested views when their match expression value matches the value of the
* switch expression.
*
* In other words:
* - you define a container element (where you place the directive with a switch expression on the
* `[ngSwitch]="..."` attribute)
* - you define inner views inside the `NgSwitch` and place a `*ngSwitchCase` attribute on the view
* root elements.
*
* Elements within `NgSwitch` but outside of a `NgSwitchCase` or `NgSwitchDefault` directives will
* be preserved at the location.
*
* The `ngSwitchCase` directive informs the parent `NgSwitch` of which view to display when the
* expression is evaluated.
* When no matching expression is found on a `ngSwitchCase` view, the `ngSwitchDefault` view is
* stamped out.
*
* \@stable
*/
var NgSwitch = (function () {
function NgSwitch() {
this._defaultUsed = false;
this._caseCount = 0;
this._lastCaseCheckIndex = 0;
this._lastCasesMatched = false;
}
Object.defineProperty(NgSwitch.prototype, "ngSwitch", {
/**
* @param {?} newValue
* @return {?}
*/
set: function (newValue) {
this._ngSwitch = newValue;
if (this._caseCount === 0) {
this._updateDefaultCases(true);
}
},
enumerable: true,
configurable: true
});
/**
* \@internal
* @return {?}
*/
NgSwitch.prototype._addCase = function () { return this._caseCount++; };
/**
* \@internal
* @param {?} view
* @return {?}
*/
NgSwitch.prototype._addDefault = function (view) {
if (!this._defaultViews) {
this._defaultViews = [];
}
this._defaultViews.push(view);
};
/**
* \@internal
* @param {?} value
* @return {?}
*/
NgSwitch.prototype._matchCase = function (value) {
var /** @type {?} */ matched = value == this._ngSwitch;
this._lastCasesMatched = this._lastCasesMatched || matched;
this._lastCaseCheckIndex++;
if (this._lastCaseCheckIndex === this._caseCount) {
this._updateDefaultCases(!this._lastCasesMatched);
this._lastCaseCheckIndex = 0;
this._lastCasesMatched = false;
}
return matched;
};
/**
* @param {?} useDefault
* @return {?}
*/
NgSwitch.prototype._updateDefaultCases = function (useDefault) {
if (this._defaultViews && useDefault !== this._defaultUsed) {
this._defaultUsed = useDefault;
for (var /** @type {?} */ i = 0; i < this._defaultViews.length; i++) {
var /** @type {?} */ defaultView = this._defaultViews[i];
defaultView.enforceState(useDefault);
}
}
};
return NgSwitch;
}());
NgSwitch.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngSwitch]' },] },
];
/**
* @nocollapse
*/
NgSwitch.ctorParameters = function () { return []; };
NgSwitch.propDecorators = {
'ngSwitch': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* \@ngModule CommonModule
*
* \@whatItDoes Creates a view that will be added/removed from the parent {\@link NgSwitch} when the
* given expression evaluate to respectively the same/different value as the switch
* expression.
*
* \@howToUse
* ```
* <container-element [ngSwitch]="switch_expression">
* <some-element *ngSwitchCase="match_expression_1">...</some-element>
* </container-element>
* ```
* \@description
*
* Insert the sub-tree when the expression evaluates to the same value as the enclosing switch
* expression.
*
* If multiple match expressions match the switch expression value, all of them are displayed.
*
* See {\@link NgSwitch} for more details and example.
*
* \@stable
*/
var NgSwitchCase = (function () {
/**
* @param {?} viewContainer
* @param {?} templateRef
* @param {?} ngSwitch
*/
function NgSwitchCase(viewContainer, templateRef, ngSwitch) {
this.ngSwitch = ngSwitch;
ngSwitch._addCase();
this._view = new SwitchView(viewContainer, templateRef);
}
/**
* @return {?}
*/
NgSwitchCase.prototype.ngDoCheck = function () { this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase)); };
return NgSwitchCase;
}());
NgSwitchCase.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngSwitchCase]' },] },
];
/**
* @nocollapse
*/
NgSwitchCase.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["X" /* ViewContainerRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["Y" /* TemplateRef */], },
{ type: NgSwitch, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] },] },
]; };
NgSwitchCase.propDecorators = {
'ngSwitchCase': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* \@ngModule CommonModule
* \@whatItDoes Creates a view that is added to the parent {\@link NgSwitch} when no case expressions
* match the
* switch expression.
*
* \@howToUse
* ```
* <container-element [ngSwitch]="switch_expression">
* <some-element *ngSwitchCase="match_expression_1">...</some-element>
* <some-other-element *ngSwitchDefault>...</some-other-element>
* </container-element>
* ```
*
* \@description
*
* Insert the sub-tree when no case expressions evaluate to the same value as the enclosing switch
* expression.
*
* See {\@link NgSwitch} for more details and example.
*
* \@stable
*/
var NgSwitchDefault = (function () {
/**
* @param {?} viewContainer
* @param {?} templateRef
* @param {?} ngSwitch
*/
function NgSwitchDefault(viewContainer, templateRef, ngSwitch) {
ngSwitch._addDefault(new SwitchView(viewContainer, templateRef));
}
return NgSwitchDefault;
}());
NgSwitchDefault.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngSwitchDefault]' },] },
];
/**
* @nocollapse
*/
NgSwitchDefault.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["X" /* ViewContainerRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["Y" /* TemplateRef */], },
{ type: NgSwitch, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] },] },
]; };
/**
* @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
*/
/**
* \@ngModule CommonModule
*
* \@whatItDoes Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization.
*
* \@howToUse
* ```
* <some-element [ngPlural]="value">
* <ng-template ngPluralCase="=0">there is nothing</ng-template>
* <ng-template ngPluralCase="=1">there is one</ng-template>
* <ng-template ngPluralCase="few">there are a few</ng-template>
* </some-element>
* ```
*
* \@description
*
* Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees
* that match the switch expression's pluralization category.
*
* To use this directive you must provide a container element that sets the `[ngPlural]` attribute
* to a switch expression. Inner elements with a `[ngPluralCase]` will display based on their
* expression:
* - if `[ngPluralCase]` is set to a value starting with `=`, it will only display if the value
* matches the switch expression exactly,
* - otherwise, the view will be treated as a "category match", and will only display if exact
* value matches aren't found and the value maps to its category for the defined locale.
*
* See http://cldr.unicode.org/index/cldr-spec/plural-rules
*
* \@experimental
*/
var NgPlural = (function () {
/**
* @param {?} _localization
*/
function NgPlural(_localization) {
this._localization = _localization;
this._caseViews = {};
}
Object.defineProperty(NgPlural.prototype, "ngPlural", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
this._switchValue = value;
this._updateView();
},
enumerable: true,
configurable: true
});
/**
* @param {?} value
* @param {?} switchView
* @return {?}
*/
NgPlural.prototype.addCase = function (value, switchView) { this._caseViews[value] = switchView; };
/**
* @return {?}
*/
NgPlural.prototype._updateView = function () {
this._clearViews();
var /** @type {?} */ cases = Object.keys(this._caseViews);
var /** @type {?} */ key = getPluralCategory(this._switchValue, cases, this._localization);
this._activateView(this._caseViews[key]);
};
/**
* @return {?}
*/
NgPlural.prototype._clearViews = function () {
if (this._activeView)
this._activeView.destroy();
};
/**
* @param {?} view
* @return {?}
*/
NgPlural.prototype._activateView = function (view) {
if (view) {
this._activeView = view;
this._activeView.create();
}
};
return NgPlural;
}());
NgPlural.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngPlural]' },] },
];
/**
* @nocollapse
*/
NgPlural.ctorParameters = function () { return [
{ type: NgLocalization, },
]; };
NgPlural.propDecorators = {
'ngPlural': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* \@ngModule CommonModule
*
* \@whatItDoes Creates a view that will be added/removed from the parent {\@link NgPlural} when the
* given expression matches the plural expression according to CLDR rules.
*
* \@howToUse
* ```
* <some-element [ngPlural]="value">
* <ng-template ngPluralCase="=0">...</ng-template>
* <ng-template ngPluralCase="other">...</ng-template>
* </some-element>
* ```
*
* See {\@link NgPlural} for more details and example.
*
* \@experimental
*/
var NgPluralCase = (function () {
/**
* @param {?} value
* @param {?} template
* @param {?} viewContainer
* @param {?} ngPlural
*/
function NgPluralCase(value, template, viewContainer, ngPlural) {
this.value = value;
var isANumber = !isNaN(Number(value));
ngPlural.addCase(isANumber ? "=" + value : value, new SwitchView(viewContainer, template));
}
return NgPluralCase;
}());
NgPluralCase.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngPluralCase]' },] },
];
/**
* @nocollapse
*/
NgPluralCase.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["Z" /* Attribute */], args: ['ngPluralCase',] },] },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["Y" /* TemplateRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["X" /* ViewContainerRef */], },
{ type: NgPlural, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */] },] },
]; };
/**
* @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
*/
/**
* \@ngModule CommonModule
*
* \@whatItDoes Update an HTML element styles.
*
* \@howToUse
* ```
* <some-element [ngStyle]="{'font-style': styleExp}">...</some-element>
*
* <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>
*
* <some-element [ngStyle]="objExp">...</some-element>
* ```
*
* \@description
*
* The styles are updated according to the value of the expression evaluation:
* - keys are style names with an optional `.<unit>` suffix (ie 'top.px', 'font-style.em'),
* - values are the values assigned to those properties (expressed in the given unit).
*
* \@stable
*/
var NgStyle = (function () {
/**
* @param {?} _differs
* @param {?} _ngEl
* @param {?} _renderer
*/
function NgStyle(_differs, _ngEl, _renderer) {
this._differs = _differs;
this._ngEl = _ngEl;
this._renderer = _renderer;
}
Object.defineProperty(NgStyle.prototype, "ngStyle", {
/**
* @param {?} v
* @return {?}
*/
set: function (v) {
this._ngStyle = v;
if (!this._differ && v) {
this._differ = this._differs.find(v).create();
}
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
NgStyle.prototype.ngDoCheck = function () {
if (this._differ) {
var /** @type {?} */ changes = this._differ.diff(this._ngStyle);
if (changes) {
this._applyChanges(changes);
}
}
};
/**
* @param {?} changes
* @return {?}
*/
NgStyle.prototype._applyChanges = function (changes) {
var _this = this;
changes.forEachRemovedItem(function (record) { return _this._setStyle(record.key, null); });
changes.forEachAddedItem(function (record) { return _this._setStyle(record.key, record.currentValue); });
changes.forEachChangedItem(function (record) { return _this._setStyle(record.key, record.currentValue); });
};
/**
* @param {?} nameAndUnit
* @param {?} value
* @return {?}
*/
NgStyle.prototype._setStyle = function (nameAndUnit, value) {
var _a = nameAndUnit.split('.'), name = _a[0], unit = _a[1];
value = value != null && unit ? "" + value + unit : value;
this._renderer.setElementStyle(this._ngEl.nativeElement, name, /** @type {?} */ (value));
};
return NgStyle;
}());
NgStyle.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngStyle]' },] },
];
/**
* @nocollapse
*/
NgStyle.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["U" /* KeyValueDiffers */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */], },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */], },
]; };
NgStyle.propDecorators = {
'ngStyle': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* @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
*/
/**
* \@ngModule CommonModule
*
* \@whatItDoes Inserts an embedded view from a prepared `TemplateRef`
*
* \@howToUse
* ```
* <ng-container *ngTemplateOutlet="templateRefExp; context: contextExp"></ng-container>
* ```
*
* \@description
*
* You can attach a context object to the `EmbeddedViewRef` by setting `[ngTemplateOutletContext]`.
* `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding
* by the local template `let` declarations.
*
* Note: using the key `$implicit` in the context object will set it's value as default.
*
* # Example
*
* {\@example common/ngTemplateOutlet/ts/module.ts region='NgTemplateOutlet'}
*
* \@experimental
*/
var NgTemplateOutlet = (function () {
/**
* @param {?} _viewContainerRef
*/
function NgTemplateOutlet(_viewContainerRef) {
this._viewContainerRef = _viewContainerRef;
}
Object.defineProperty(NgTemplateOutlet.prototype, "ngOutletContext", {
/**
* @deprecated v4.0.0 - Renamed to ngTemplateOutletContext.
* @param {?} context
* @return {?}
*/
set: function (context) { this.ngTemplateOutletContext = context; },
enumerable: true,
configurable: true
});
/**
* @param {?} changes
* @return {?}
*/
NgTemplateOutlet.prototype.ngOnChanges = function (changes) {
if (this._viewRef) {
this._viewContainerRef.remove(this._viewContainerRef.indexOf(this._viewRef));
}
if (this.ngTemplateOutlet) {
this._viewRef = this._viewContainerRef.createEmbeddedView(this.ngTemplateOutlet, this.ngTemplateOutletContext);
}
};
return NgTemplateOutlet;
}());
NgTemplateOutlet.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], args: [{ selector: '[ngTemplateOutlet]' },] },
];
/**
* @nocollapse
*/
NgTemplateOutlet.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["X" /* ViewContainerRef */], },
]; };
NgTemplateOutlet.propDecorators = {
'ngTemplateOutletContext': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngTemplateOutlet': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
'ngOutletContext': [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */] },],
};
/**
* @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
*/
/**
* A collection of Angular directives that are likely to be used in each and every Angular
* application.
*/
var COMMON_DIRECTIVES = [
NgClass,
NgComponentOutlet,
NgForOf,
NgIf,
NgTemplateOutlet,
NgStyle,
NgSwitch,
NgSwitchCase,
NgSwitchDefault,
NgPlural,
NgPluralCase,
];
/**
* A collection of deprecated directives that are no longer part of the core module.
*/
/**
* @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
*/
/**
* @param {?} type
* @param {?} value
* @return {?}
*/
function invalidPipeArgumentError(type, value) {
return Error("InvalidPipeArgument: '" + value + "' for pipe '" + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(type) + "'");
}
/**
* @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
*/
var ObservableStrategy = (function () {
function ObservableStrategy() {
}
/**
* @param {?} async
* @param {?} updateLatestValue
* @return {?}
*/
ObservableStrategy.prototype.createSubscription = function (async, updateLatestValue) {
return async.subscribe({ next: updateLatestValue, error: function (e) { throw e; } });
};
/**
* @param {?} subscription
* @return {?}
*/
ObservableStrategy.prototype.dispose = function (subscription) { subscription.unsubscribe(); };
/**
* @param {?} subscription
* @return {?}
*/
ObservableStrategy.prototype.onDestroy = function (subscription) { subscription.unsubscribe(); };
return ObservableStrategy;
}());
var PromiseStrategy = (function () {
function PromiseStrategy() {
}
/**
* @param {?} async
* @param {?} updateLatestValue
* @return {?}
*/
PromiseStrategy.prototype.createSubscription = function (async, updateLatestValue) {
return async.then(updateLatestValue, function (e) { throw e; });
};
/**
* @param {?} subscription
* @return {?}
*/
PromiseStrategy.prototype.dispose = function (subscription) { };
/**
* @param {?} subscription
* @return {?}
*/
PromiseStrategy.prototype.onDestroy = function (subscription) { };
return PromiseStrategy;
}());
var _promiseStrategy = new PromiseStrategy();
var _observableStrategy = new ObservableStrategy();
/**
* \@ngModule CommonModule
* \@whatItDoes Unwraps a value from an asynchronous primitive.
* \@howToUse `observable_or_promise_expression | async`
* \@description
* The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has
* emitted. When a new value is emitted, the `async` pipe marks the component to be checked for
* changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid
* potential memory leaks.
*
*
* ## Examples
*
* This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the
* promise.
*
* {\@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'}
*
* It's also possible to use `async` with Observables. The example below binds the `time` Observable
* to the view. The Observable continuously updates the view with the current time.
*
* {\@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'}
*
* \@stable
*/
var AsyncPipe = (function () {
/**
* @param {?} _ref
*/
function AsyncPipe(_ref) {
this._ref = _ref;
this._latestValue = null;
this._latestReturnedValue = null;
this._subscription = null;
this._obj = null;
this._strategy = ((null));
}
/**
* @return {?}
*/
AsyncPipe.prototype.ngOnDestroy = function () {
if (this._subscription) {
this._dispose();
}
};
/**
* @param {?} obj
* @return {?}
*/
AsyncPipe.prototype.transform = function (obj) {
if (!this._obj) {
if (obj) {
this._subscribe(obj);
}
this._latestReturnedValue = this._latestValue;
return this._latestValue;
}
if (obj !== this._obj) {
this._dispose();
return this.transform(/** @type {?} */ (obj));
}
if (this._latestValue === this._latestReturnedValue) {
return this._latestReturnedValue;
}
this._latestReturnedValue = this._latestValue;
return __WEBPACK_IMPORTED_MODULE_0__angular_core__["_0" /* WrappedValue */].wrap(this._latestValue);
};
/**
* @param {?} obj
* @return {?}
*/
AsyncPipe.prototype._subscribe = function (obj) {
var _this = this;
this._obj = obj;
this._strategy = this._selectStrategy(obj);
this._subscription = this._strategy.createSubscription(obj, function (value) { return _this._updateLatestValue(obj, value); });
};
/**
* @param {?} obj
* @return {?}
*/
AsyncPipe.prototype._selectStrategy = function (obj) {
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["f" /* ɵisPromise */])(obj)) {
return _promiseStrategy;
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["g" /* ɵisObservable */])(obj)) {
return _observableStrategy;
}
throw invalidPipeArgumentError(AsyncPipe, obj);
};
/**
* @return {?}
*/
AsyncPipe.prototype._dispose = function () {
this._strategy.dispose(/** @type {?} */ ((this._subscription)));
this._latestValue = null;
this._latestReturnedValue = null;
this._subscription = null;
this._obj = null;
};
/**
* @param {?} async
* @param {?} value
* @return {?}
*/
AsyncPipe.prototype._updateLatestValue = function (async, value) {
if (async === this._obj) {
this._latestValue = value;
this._ref.markForCheck();
}
};
return AsyncPipe;
}());
AsyncPipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'async', pure: false },] },
];
/**
* @nocollapse
*/
AsyncPipe.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_2" /* ChangeDetectorRef */], },
]; };
/**
* @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
*/
/**
* Transforms text to lowercase.
*
* {\@example common/pipes/ts/lowerupper_pipe.ts region='LowerUpperPipe' }
*
* \@stable
*/
var LowerCasePipe = (function () {
function LowerCasePipe() {
}
/**
* @param {?} value
* @return {?}
*/
LowerCasePipe.prototype.transform = function (value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(LowerCasePipe, value);
}
return value.toLowerCase();
};
return LowerCasePipe;
}());
LowerCasePipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'lowercase' },] },
];
/**
* @nocollapse
*/
LowerCasePipe.ctorParameters = function () { return []; };
/**
* Helper method to transform a single word to titlecase.
*
* \@stable
* @param {?} word
* @return {?}
*/
function titleCaseWord(word) {
if (!word)
return word;
return word[0].toUpperCase() + word.substr(1).toLowerCase();
}
/**
* Transforms text to titlecase.
*
* \@stable
*/
var TitleCasePipe = (function () {
function TitleCasePipe() {
}
/**
* @param {?} value
* @return {?}
*/
TitleCasePipe.prototype.transform = function (value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(TitleCasePipe, value);
}
return value.split(/\b/g).map(function (word) { return titleCaseWord(word); }).join('');
};
return TitleCasePipe;
}());
TitleCasePipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'titlecase' },] },
];
/**
* @nocollapse
*/
TitleCasePipe.ctorParameters = function () { return []; };
/**
* Transforms text to uppercase.
*
* \@stable
*/
var UpperCasePipe = (function () {
function UpperCasePipe() {
}
/**
* @param {?} value
* @return {?}
*/
UpperCasePipe.prototype.transform = function (value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(UpperCasePipe, value);
}
return value.toUpperCase();
};
return UpperCasePipe;
}());
UpperCasePipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'uppercase' },] },
];
/**
* @nocollapse
*/
UpperCasePipe.ctorParameters = function () { return []; };
var NumberFormatStyle = {};
NumberFormatStyle.Decimal = 0;
NumberFormatStyle.Percent = 1;
NumberFormatStyle.Currency = 2;
NumberFormatStyle[NumberFormatStyle.Decimal] = "Decimal";
NumberFormatStyle[NumberFormatStyle.Percent] = "Percent";
NumberFormatStyle[NumberFormatStyle.Currency] = "Currency";
var NumberFormatter = (function () {
function NumberFormatter() {
}
/**
* @param {?} num
* @param {?} locale
* @param {?} style
* @param {?=} __3
* @return {?}
*/
NumberFormatter.format = function (num, locale, style, _a) {
var _b = _a === void 0 ? {} : _a, minimumIntegerDigits = _b.minimumIntegerDigits, minimumFractionDigits = _b.minimumFractionDigits, maximumFractionDigits = _b.maximumFractionDigits, currency = _b.currency, _c = _b.currencyAsSymbol, currencyAsSymbol = _c === void 0 ? false : _c;
var /** @type {?} */ options = {
minimumIntegerDigits: minimumIntegerDigits,
minimumFractionDigits: minimumFractionDigits,
maximumFractionDigits: maximumFractionDigits,
style: NumberFormatStyle[style].toLowerCase()
};
if (style == NumberFormatStyle.Currency) {
options.currency = typeof currency == 'string' ? currency : undefined;
options.currencyDisplay = currencyAsSymbol ? 'symbol' : 'code';
}
return new Intl.NumberFormat(locale, options).format(num);
};
return NumberFormatter;
}());
var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsazZEwGjJ']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|J+|j+|m+|s+|a|z|Z|G+|w+))(.*)/;
var PATTERN_ALIASES = {
// Keys are quoted so they do not get renamed during closure compilation.
'yMMMdjms': datePartGetterFactory(combine([
digitCondition('year', 1),
nameCondition('month', 3),
digitCondition('day', 1),
digitCondition('hour', 1),
digitCondition('minute', 1),
digitCondition('second', 1),
])),
'yMdjm': datePartGetterFactory(combine([
digitCondition('year', 1), digitCondition('month', 1), digitCondition('day', 1),
digitCondition('hour', 1), digitCondition('minute', 1)
])),
'yMMMMEEEEd': datePartGetterFactory(combine([
digitCondition('year', 1), nameCondition('month', 4), nameCondition('weekday', 4),
digitCondition('day', 1)
])),
'yMMMMd': datePartGetterFactory(combine([digitCondition('year', 1), nameCondition('month', 4), digitCondition('day', 1)])),
'yMMMd': datePartGetterFactory(combine([digitCondition('year', 1), nameCondition('month', 3), digitCondition('day', 1)])),
'yMd': datePartGetterFactory(combine([digitCondition('year', 1), digitCondition('month', 1), digitCondition('day', 1)])),
'jms': datePartGetterFactory(combine([digitCondition('hour', 1), digitCondition('second', 1), digitCondition('minute', 1)])),
'jm': datePartGetterFactory(combine([digitCondition('hour', 1), digitCondition('minute', 1)]))
};
var DATE_FORMATS = {
// Keys are quoted so they do not get renamed.
'yyyy': datePartGetterFactory(digitCondition('year', 4)),
'yy': datePartGetterFactory(digitCondition('year', 2)),
'y': datePartGetterFactory(digitCondition('year', 1)),
'MMMM': datePartGetterFactory(nameCondition('month', 4)),
'MMM': datePartGetterFactory(nameCondition('month', 3)),
'MM': datePartGetterFactory(digitCondition('month', 2)),
'M': datePartGetterFactory(digitCondition('month', 1)),
'LLLL': datePartGetterFactory(nameCondition('month', 4)),
'L': datePartGetterFactory(nameCondition('month', 1)),
'dd': datePartGetterFactory(digitCondition('day', 2)),
'd': datePartGetterFactory(digitCondition('day', 1)),
'HH': digitModifier(hourExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 2), false)))),
'H': hourExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), false))),
'hh': digitModifier(hourExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 2), true)))),
'h': hourExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), true))),
'jj': datePartGetterFactory(digitCondition('hour', 2)),
'j': datePartGetterFactory(digitCondition('hour', 1)),
'mm': digitModifier(datePartGetterFactory(digitCondition('minute', 2))),
'm': datePartGetterFactory(digitCondition('minute', 1)),
'ss': digitModifier(datePartGetterFactory(digitCondition('second', 2))),
's': datePartGetterFactory(digitCondition('second', 1)),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit
// fractions
'sss': datePartGetterFactory(digitCondition('second', 3)),
'EEEE': datePartGetterFactory(nameCondition('weekday', 4)),
'EEE': datePartGetterFactory(nameCondition('weekday', 3)),
'EE': datePartGetterFactory(nameCondition('weekday', 2)),
'E': datePartGetterFactory(nameCondition('weekday', 1)),
'a': hourClockExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), true))),
'Z': timeZoneGetter('short'),
'z': timeZoneGetter('long'),
'ww': datePartGetterFactory({}),
// first Thursday of the year. not support ?
'w': datePartGetterFactory({}),
// of the year not support ?
'G': datePartGetterFactory(nameCondition('era', 1)),
'GG': datePartGetterFactory(nameCondition('era', 2)),
'GGG': datePartGetterFactory(nameCondition('era', 3)),
'GGGG': datePartGetterFactory(nameCondition('era', 4))
};
/**
* @param {?} inner
* @return {?}
*/
function digitModifier(inner) {
return function (date, locale) {
var /** @type {?} */ result = inner(date, locale);
return result.length == 1 ? '0' + result : result;
};
}
/**
* @param {?} inner
* @return {?}
*/
function hourClockExtractor(inner) {
return function (date, locale) { return inner(date, locale).split(' ')[1]; };
}
/**
* @param {?} inner
* @return {?}
*/
function hourExtractor(inner) {
return function (date, locale) { return inner(date, locale).split(' ')[0]; };
}
/**
* @param {?} date
* @param {?} locale
* @param {?} options
* @return {?}
*/
function intlDateFormat(date, locale, options) {
return new Intl.DateTimeFormat(locale, options).format(date).replace(/[\u200e\u200f]/g, '');
}
/**
* @param {?} timezone
* @return {?}
*/
function timeZoneGetter(timezone) {
// To workaround `Intl` API restriction for single timezone let format with 24 hours
var /** @type {?} */ options = { hour: '2-digit', hour12: false, timeZoneName: timezone };
return function (date, locale) {
var /** @type {?} */ result = intlDateFormat(date, locale, options);
// Then extract first 3 letters that related to hours
return result ? result.substring(3) : '';
};
}
/**
* @param {?} options
* @param {?} value
* @return {?}
*/
function hour12Modify(options, value) {
options.hour12 = value;
return options;
}
/**
* @param {?} prop
* @param {?} len
* @return {?}
*/
function digitCondition(prop, len) {
var /** @type {?} */ result = {};
result[prop] = len === 2 ? '2-digit' : 'numeric';
return result;
}
/**
* @param {?} prop
* @param {?} len
* @return {?}
*/
function nameCondition(prop, len) {
var /** @type {?} */ result = {};
if (len < 4) {
result[prop] = len > 1 ? 'short' : 'narrow';
}
else {
result[prop] = 'long';
}
return result;
}
/**
* @param {?} options
* @return {?}
*/
function combine(options) {
return ((Object)).assign.apply(((Object)), [{}].concat(options));
}
/**
* @param {?} ret
* @return {?}
*/
function datePartGetterFactory(ret) {
return function (date, locale) { return intlDateFormat(date, locale, ret); };
}
var DATE_FORMATTER_CACHE = new Map();
/**
* @param {?} format
* @param {?} date
* @param {?} locale
* @return {?}
*/
function dateFormatter(format, date, locale) {
var /** @type {?} */ fn = PATTERN_ALIASES[format];
if (fn)
return fn(date, locale);
var /** @type {?} */ cacheKey = format;
var /** @type {?} */ parts = DATE_FORMATTER_CACHE.get(cacheKey);
if (!parts) {
parts = [];
var /** @type {?} */ match = void 0;
DATE_FORMATS_SPLIT.exec(format);
var /** @type {?} */ _format = format;
while (_format) {
match = DATE_FORMATS_SPLIT.exec(_format);
if (match) {
parts = parts.concat(match.slice(1));
_format = ((parts.pop()));
}
else {
parts.push(_format);
_format = null;
}
}
DATE_FORMATTER_CACHE.set(cacheKey, parts);
}
return parts.reduce(function (text, part) {
var /** @type {?} */ fn = DATE_FORMATS[part];
return text + (fn ? fn(date, locale) : partToTime(part));
}, '');
}
/**
* @param {?} part
* @return {?}
*/
function partToTime(part) {
return part === '\'\'' ? '\'' : part.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
}
var DateFormatter = (function () {
function DateFormatter() {
}
/**
* @param {?} date
* @param {?} locale
* @param {?} pattern
* @return {?}
*/
DateFormatter.format = function (date, locale, pattern) {
return dateFormatter(pattern, date, locale);
};
return DateFormatter;
}());
/**
* @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
*/
var _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
/**
* @param {?} pipe
* @param {?} locale
* @param {?} value
* @param {?} style
* @param {?=} digits
* @param {?=} currency
* @param {?=} currencyAsSymbol
* @return {?}
*/
function formatNumber(pipe, locale, value, style, digits, currency, currencyAsSymbol) {
if (currency === void 0) { currency = null; }
if (currencyAsSymbol === void 0) { currencyAsSymbol = false; }
if (value == null)
return null;
// Convert strings to numbers
value = typeof value === 'string' && isNumeric(value) ? +value : value;
if (typeof value !== 'number') {
throw invalidPipeArgumentError(pipe, value);
}
var /** @type {?} */ minInt = undefined;
var /** @type {?} */ minFraction = undefined;
var /** @type {?} */ maxFraction = undefined;
if (style !== NumberFormatStyle.Currency) {
// rely on Intl default for currency
minInt = 1;
minFraction = 0;
maxFraction = 3;
}
if (digits) {
var /** @type {?} */ parts = digits.match(_NUMBER_FORMAT_REGEXP);
if (parts === null) {
throw new Error(digits + " is not a valid digit info for number pipes");
}
if (parts[1] != null) {
minInt = parseIntAutoRadix(parts[1]);
}
if (parts[3] != null) {
minFraction = parseIntAutoRadix(parts[3]);
}
if (parts[5] != null) {
maxFraction = parseIntAutoRadix(parts[5]);
}
}
return NumberFormatter.format(/** @type {?} */ (value), locale, style, {
minimumIntegerDigits: minInt,
minimumFractionDigits: minFraction,
maximumFractionDigits: maxFraction,
currency: currency,
currencyAsSymbol: currencyAsSymbol,
});
}
/**
* \@ngModule CommonModule
* \@whatItDoes Formats a number according to locale rules.
* \@howToUse `number_expression | number[:digitInfo]`
*
* Formats a number as text. Group sizing and separator and other locale-specific
* configurations are based on the active locale.
*
* where `expression` is a number:
* - `digitInfo` is a `string` which has a following format: <br>
* <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>
* - `minIntegerDigits` is the minimum number of integer digits to use. Defaults to `1`.
* - `minFractionDigits` is the minimum number of digits after fraction. Defaults to `0`.
* - `maxFractionDigits` is the maximum number of digits after fraction. Defaults to `3`.
*
* For more information on the acceptable range for each of these numbers and other
* details see your native internationalization library.
*
* WARNING: this pipe uses the Internationalization API which is not yet available in all browsers
* and may require a polyfill. See {\@linkDocs guide/browser-support} for details.
*
* ### Example
*
* {\@example common/pipes/ts/number_pipe.ts region='NumberPipe'}
*
* \@stable
*/
var DecimalPipe = (function () {
/**
* @param {?} _locale
*/
function DecimalPipe(_locale) {
this._locale = _locale;
}
/**
* @param {?} value
* @param {?=} digits
* @return {?}
*/
DecimalPipe.prototype.transform = function (value, digits) {
return formatNumber(DecimalPipe, this._locale, value, NumberFormatStyle.Decimal, digits);
};
return DecimalPipe;
}());
DecimalPipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'number' },] },
];
/**
* @nocollapse
*/
DecimalPipe.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [__WEBPACK_IMPORTED_MODULE_0__angular_core__["Q" /* LOCALE_ID */],] },] },
]; };
/**
* \@ngModule CommonModule
* \@whatItDoes Formats a number as a percentage according to locale rules.
* \@howToUse `number_expression | percent[:digitInfo]`
*
* \@description
*
* Formats a number as percentage.
*
* - `digitInfo` See {\@link DecimalPipe} for detailed description.
*
* WARNING: this pipe uses the Internationalization API which is not yet available in all browsers
* and may require a polyfill. See {\@linkDocs guide/browser-support} for details.
*
* ### Example
*
* {\@example common/pipes/ts/number_pipe.ts region='PercentPipe'}
*
* \@stable
*/
var PercentPipe = (function () {
/**
* @param {?} _locale
*/
function PercentPipe(_locale) {
this._locale = _locale;
}
/**
* @param {?} value
* @param {?=} digits
* @return {?}
*/
PercentPipe.prototype.transform = function (value, digits) {
return formatNumber(PercentPipe, this._locale, value, NumberFormatStyle.Percent, digits);
};
return PercentPipe;
}());
PercentPipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'percent' },] },
];
/**
* @nocollapse
*/
PercentPipe.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [__WEBPACK_IMPORTED_MODULE_0__angular_core__["Q" /* LOCALE_ID */],] },] },
]; };
/**
* \@ngModule CommonModule
* \@whatItDoes Formats a number as currency using locale rules.
* \@howToUse `number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]`
* \@description
*
* Use `currency` to format a number as currency.
*
* - `currencyCode` is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, such
* as `USD` for the US dollar and `EUR` for the euro.
* - `symbolDisplay` is a boolean indicating whether to use the currency symbol or code.
* - `true`: use symbol (e.g. `$`).
* - `false`(default): use code (e.g. `USD`).
* - `digitInfo` See {\@link DecimalPipe} for detailed description.
*
* WARNING: this pipe uses the Internationalization API which is not yet available in all browsers
* and may require a polyfill. See {\@linkDocs guide/browser-support} for details.
*
* ### Example
*
* {\@example common/pipes/ts/number_pipe.ts region='CurrencyPipe'}
*
* \@stable
*/
var CurrencyPipe = (function () {
/**
* @param {?} _locale
*/
function CurrencyPipe(_locale) {
this._locale = _locale;
}
/**
* @param {?} value
* @param {?=} currencyCode
* @param {?=} symbolDisplay
* @param {?=} digits
* @return {?}
*/
CurrencyPipe.prototype.transform = function (value, currencyCode, symbolDisplay, digits) {
if (currencyCode === void 0) { currencyCode = 'USD'; }
if (symbolDisplay === void 0) { symbolDisplay = false; }
return formatNumber(CurrencyPipe, this._locale, value, NumberFormatStyle.Currency, digits, currencyCode, symbolDisplay);
};
return CurrencyPipe;
}());
CurrencyPipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'currency' },] },
];
/**
* @nocollapse
*/
CurrencyPipe.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [__WEBPACK_IMPORTED_MODULE_0__angular_core__["Q" /* LOCALE_ID */],] },] },
]; };
/**
* @param {?} text
* @return {?}
*/
function parseIntAutoRadix(text) {
var /** @type {?} */ result = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
}
/**
* @param {?} value
* @return {?}
*/
function isNumeric(value) {
return !isNaN(value - parseFloat(value));
}
/**
* @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
*/
var ISO8601_DATE_REGEX = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
/**
* \@ngModule CommonModule
* \@whatItDoes Formats a date according to locale rules.
* \@howToUse `date_expression | date[:format]`
* \@description
*
* Where:
* - `expression` is a date object or a number (milliseconds since UTC epoch) or an ISO string
* (https://www.w3.org/TR/NOTE-datetime).
* - `format` indicates which date/time components to include. The format can be predefined as
* shown below or custom as shown in the table.
* - `'medium'`: equivalent to `'yMMMdjms'` (e.g. `Sep 3, 2010, 12:05:08 PM` for `en-US`)
* - `'short'`: equivalent to `'yMdjm'` (e.g. `9/3/2010, 12:05 PM` for `en-US`)
* - `'fullDate'`: equivalent to `'yMMMMEEEEd'` (e.g. `Friday, September 3, 2010` for `en-US`)
* - `'longDate'`: equivalent to `'yMMMMd'` (e.g. `September 3, 2010` for `en-US`)
* - `'mediumDate'`: equivalent to `'yMMMd'` (e.g. `Sep 3, 2010` for `en-US`)
* - `'shortDate'`: equivalent to `'yMd'` (e.g. `9/3/2010` for `en-US`)
* - `'mediumTime'`: equivalent to `'jms'` (e.g. `12:05:08 PM` for `en-US`)
* - `'shortTime'`: equivalent to `'jm'` (e.g. `12:05 PM` for `en-US`)
*
*
* | Component | Symbol | Narrow | Short Form | Long Form | Numeric | 2-digit |
* |-----------|:------:|--------|--------------|-------------------|-----------|-----------|
* | era | G | G (A) | GGG (AD) | GGGG (Anno Domini)| - | - |
* | year | y | - | - | - | y (2015) | yy (15) |
* | month | M | L (S) | MMM (Sep) | MMMM (September) | M (9) | MM (09) |
* | day | d | - | - | - | d (3) | dd (03) |
* | weekday | E | E (S) | EEE (Sun) | EEEE (Sunday) | - | - |
* | hour | j | - | - | - | j (13) | jj (13) |
* | hour12 | h | - | - | - | h (1 PM) | hh (01 PM)|
* | hour24 | H | - | - | - | H (13) | HH (13) |
* | minute | m | - | - | - | m (5) | mm (05) |
* | second | s | - | - | - | s (9) | ss (09) |
* | timezone | z | - | - | z (Pacific Standard Time)| - | - |
* | timezone | Z | - | Z (GMT-8:00) | - | - | - |
* | timezone | a | - | a (PM) | - | - | - |
*
* In javascript, only the components specified will be respected (not the ordering,
* punctuations, ...) and details of the formatting will be dependent on the locale.
*
* Timezone of the formatted text will be the local system timezone of the end-user's machine.
*
* When the expression is a ISO string without time (e.g. 2016-09-19) the time zone offset is not
* applied and the formatted text will have the same day, month and year of the expression.
*
* WARNINGS:
* - this pipe is marked as pure hence it will not be re-evaluated when the input is mutated.
* Instead users should treat the date as an immutable object and change the reference when the
* pipe needs to re-run (this is to avoid reformatting the date on every change detection run
* which would be an expensive operation).
* - this pipe uses the Internationalization API. Therefore it is only reliable in Chrome and Opera
* browsers.
*
* ### Examples
*
* Assuming `dateObj` is (year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11)
* in the _local_ time and locale is 'en-US':
*
* ```
* {{ dateObj | date }} // output is 'Jun 15, 2015'
* {{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
* {{ dateObj | date:'shortTime' }} // output is '9:43 PM'
* {{ dateObj | date:'mmss' }} // output is '43:11'
* ```
*
* {\@example common/pipes/ts/date_pipe.ts region='DatePipe'}
*
* \@stable
*/
var DatePipe = (function () {
/**
* @param {?} _locale
*/
function DatePipe(_locale) {
this._locale = _locale;
}
/**
* @param {?} value
* @param {?=} pattern
* @return {?}
*/
DatePipe.prototype.transform = function (value, pattern) {
if (pattern === void 0) { pattern = 'mediumDate'; }
var /** @type {?} */ date;
if (isBlank(value) || value !== value)
return null;
if (typeof value === 'string') {
value = value.trim();
}
if (isDate(value)) {
date = value;
}
else if (isNumeric(value)) {
date = new Date(parseFloat(value));
}
else if (typeof value === 'string' && /^(\d{4}-\d{1,2}-\d{1,2})$/.test(value)) {
/**
* For ISO Strings without time the day, month and year must be extracted from the ISO String
* before Date creation to avoid time offset and errors in the new Date.
* If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new
* date, some browsers (e.g. IE 9) will throw an invalid Date error
* If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset
* is applied
* Note: ISO months are 0 for January, 1 for February, ...
*/
var _a = value.split('-').map(function (val) { return parseInt(val, 10); }), y = _a[0], m = _a[1], d = _a[2];
date = new Date(y, m - 1, d);
}
else {
date = new Date(value);
}
if (!isDate(date)) {
var /** @type {?} */ match = void 0;
if ((typeof value === 'string') && (match = value.match(ISO8601_DATE_REGEX))) {
date = isoStringToDate(match);
}
else {
throw invalidPipeArgumentError(DatePipe, value);
}
}
return DateFormatter.format(date, this._locale, DatePipe._ALIASES[pattern] || pattern);
};
return DatePipe;
}());
/**
* \@internal
*/
DatePipe._ALIASES = {
'medium': 'yMMMdjms',
'short': 'yMdjm',
'fullDate': 'yMMMMEEEEd',
'longDate': 'yMMMMd',
'mediumDate': 'yMMMd',
'shortDate': 'yMd',
'mediumTime': 'jms',
'shortTime': 'jm'
};
DatePipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'date', pure: true },] },
];
/**
* @nocollapse
*/
DatePipe.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [__WEBPACK_IMPORTED_MODULE_0__angular_core__["Q" /* LOCALE_ID */],] },] },
]; };
/**
* @param {?} obj
* @return {?}
*/
function isBlank(obj) {
return obj == null || obj === '';
}
/**
* @param {?} obj
* @return {?}
*/
function isDate(obj) {
return obj instanceof Date && !isNaN(obj.valueOf());
}
/**
* @param {?} match
* @return {?}
*/
function isoStringToDate(match) {
var /** @type {?} */ date = new Date(0);
var /** @type {?} */ tzHour = 0;
var /** @type {?} */ tzMin = 0;
var /** @type {?} */ dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear;
var /** @type {?} */ timeSetter = match[8] ? date.setUTCHours : date.setHours;
if (match[9]) {
tzHour = toInt(match[9] + match[10]);
tzMin = toInt(match[9] + match[11]);
}
dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
var /** @type {?} */ h = toInt(match[4] || '0') - tzHour;
var /** @type {?} */ m = toInt(match[5] || '0') - tzMin;
var /** @type {?} */ s = toInt(match[6] || '0');
var /** @type {?} */ ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
}
/**
* @param {?} str
* @return {?}
*/
function toInt(str) {
return parseInt(str, 10);
}
/**
* @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
*/
var _INTERPOLATION_REGEXP = /#/g;
/**
* \@ngModule CommonModule
* \@whatItDoes Maps a value to a string that pluralizes the value according to locale rules.
* \@howToUse `expression | i18nPlural:mapping`
* \@description
*
* Where:
* - `expression` is a number.
* - `mapping` is an object that mimics the ICU format, see
* http://userguide.icu-project.org/formatparse/messages
*
* ## Example
*
* {\@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'}
*
* \@experimental
*/
var I18nPluralPipe = (function () {
/**
* @param {?} _localization
*/
function I18nPluralPipe(_localization) {
this._localization = _localization;
}
/**
* @param {?} value
* @param {?} pluralMap
* @return {?}
*/
I18nPluralPipe.prototype.transform = function (value, pluralMap) {
if (value == null)
return '';
if (typeof pluralMap !== 'object' || pluralMap === null) {
throw invalidPipeArgumentError(I18nPluralPipe, pluralMap);
}
var /** @type {?} */ key = getPluralCategory(value, Object.keys(pluralMap), this._localization);
return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
};
return I18nPluralPipe;
}());
I18nPluralPipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'i18nPlural', pure: true },] },
];
/**
* @nocollapse
*/
I18nPluralPipe.ctorParameters = function () { return [
{ type: NgLocalization, },
]; };
/**
* @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
*/
/**
* \@ngModule CommonModule
* \@whatItDoes Generic selector that displays the string that matches the current value.
* \@howToUse `expression | i18nSelect:mapping`
* \@description
*
* Where `mapping` is an object that indicates the text that should be displayed
* for different values of the provided `expression`.
* If none of the keys of the mapping match the value of the `expression`, then the content
* of the `other` key is returned when present, otherwise an empty string is returned.
*
* ## Example
*
* {\@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'}
*
* \@experimental
*/
var I18nSelectPipe = (function () {
function I18nSelectPipe() {
}
/**
* @param {?} value
* @param {?} mapping
* @return {?}
*/
I18nSelectPipe.prototype.transform = function (value, mapping) {
if (value == null)
return '';
if (typeof mapping !== 'object' || typeof value !== 'string') {
throw invalidPipeArgumentError(I18nSelectPipe, mapping);
}
if (mapping.hasOwnProperty(value)) {
return mapping[value];
}
if (mapping.hasOwnProperty('other')) {
return mapping['other'];
}
return '';
};
return I18nSelectPipe;
}());
I18nSelectPipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'i18nSelect', pure: true },] },
];
/**
* @nocollapse
*/
I18nSelectPipe.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* \@ngModule CommonModule
* \@whatItDoes Converts value into JSON string.
* \@howToUse `expression | json`
* \@description
*
* Converts value into string using `JSON.stringify`. Useful for debugging.
*
* ### Example
* {\@example common/pipes/ts/json_pipe.ts region='JsonPipe'}
*
* \@stable
*/
var JsonPipe = (function () {
function JsonPipe() {
}
/**
* @param {?} value
* @return {?}
*/
JsonPipe.prototype.transform = function (value) { return JSON.stringify(value, null, 2); };
return JsonPipe;
}());
JsonPipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'json', pure: false },] },
];
/**
* @nocollapse
*/
JsonPipe.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* \@ngModule CommonModule
* \@whatItDoes Creates a new List or String containing a subset (slice) of the elements.
* \@howToUse `array_or_string_expression | slice:start[:end]`
* \@description
*
* Where the input expression is a `List` or `String`, and:
* - `start`: The starting index of the subset to return.
* - **a positive integer**: return the item at `start` index and all items after
* in the list or string expression.
* - **a negative integer**: return the item at `start` index from the end and all items after
* in the list or string expression.
* - **if positive and greater than the size of the expression**: return an empty list or string.
* - **if negative and greater than the size of the expression**: return entire list or string.
* - `end`: The ending index of the subset to return.
* - **omitted**: return all items until the end.
* - **if positive**: return all items before `end` index of the list or string.
* - **if negative**: return all items before `end` index from the end of the list or string.
*
* All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()`
* and `String.prototype.slice()`.
*
* When operating on a [List], the returned list is always a copy even when all
* the elements are being returned.
*
* When operating on a blank value, the pipe returns the blank value.
*
* ## List Example
*
* This `ngFor` example:
*
* {\@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'}
*
* produces the following:
*
* <li>b</li>
* <li>c</li>
*
* ## String Examples
*
* {\@example common/pipes/ts/slice_pipe.ts region='SlicePipe_string'}
*
* \@stable
*/
var SlicePipe = (function () {
function SlicePipe() {
}
/**
* @param {?} value
* @param {?} start
* @param {?=} end
* @return {?}
*/
SlicePipe.prototype.transform = function (value, start, end) {
if (value == null)
return value;
if (!this.supports(value)) {
throw invalidPipeArgumentError(SlicePipe, value);
}
return value.slice(start, end);
};
/**
* @param {?} obj
* @return {?}
*/
SlicePipe.prototype.supports = function (obj) { return typeof obj === 'string' || Array.isArray(obj); };
return SlicePipe;
}());
SlicePipe.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], args: [{ name: 'slice', pure: false },] },
];
/**
* @nocollapse
*/
SlicePipe.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* @module
* @description
* This module provides a set of common Pipes.
*/
/**
* A collection of Angular pipes that are likely to be used in each and every application.
*/
var COMMON_PIPES = [
AsyncPipe,
UpperCasePipe,
LowerCasePipe,
JsonPipe,
SlicePipe,
DecimalPipe,
PercentPipe,
TitleCasePipe,
CurrencyPipe,
DatePipe,
I18nPluralPipe,
I18nSelectPipe,
];
/**
* @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
*/
/**
* The module that includes all the basic Angular directives like {\@link NgIf}, {\@link NgForOf}, ...
*
* \@stable
*/
var CommonModule = (function () {
function CommonModule() {
}
return CommonModule;
}());
CommonModule.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */], args: [{
declarations: [COMMON_DIRECTIVES, COMMON_PIPES],
exports: [COMMON_DIRECTIVES, COMMON_PIPES],
providers: [
{ provide: NgLocalization, useClass: NgLocaleLocalization },
],
},] },
];
/**
* @nocollapse
*/
CommonModule.ctorParameters = function () { return []; };
/**
* @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
*/
var PLATFORM_BROWSER_ID = 'browser';
var PLATFORM_SERVER_ID = 'server';
var PLATFORM_WORKER_APP_ID = 'browserWorkerApp';
var PLATFORM_WORKER_UI_ID = 'browserWorkerUi';
/**
* Returns whether a platform id represents a browser platform.
* \@experimental
* @param {?} platformId
* @return {?}
*/
function isPlatformBrowser(platformId) {
return platformId === PLATFORM_BROWSER_ID;
}
/**
* Returns whether a platform id represents a server platform.
* \@experimental
* @param {?} platformId
* @return {?}
*/
function isPlatformServer(platformId) {
return platformId === PLATFORM_SERVER_ID;
}
/**
* Returns whether a platform id represents a web worker app platform.
* \@experimental
* @param {?} platformId
* @return {?}
*/
function isPlatformWorkerApp(platformId) {
return platformId === PLATFORM_WORKER_APP_ID;
}
/**
* Returns whether a platform id represents a web worker UI platform.
* \@experimental
* @param {?} platformId
* @return {?}
*/
function isPlatformWorkerUi(platformId) {
return platformId === PLATFORM_WORKER_UI_ID;
}
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
var VERSION = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["u" /* Version */]('4.1.1');
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=common.es5.js.map
/***/ }),
/* 18 */,
/* 19 */,
/* 20 */,
/* 21 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 22 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_common__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_core__ = __webpack_require__(1);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BrowserModule; });
/* unused harmony export platformBrowser */
/* unused harmony export Meta */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Title; });
/* unused harmony export disableDebugTools */
/* unused harmony export enableDebugTools */
/* unused harmony export By */
/* unused harmony export NgProbeToken */
/* unused harmony export DOCUMENT */
/* unused harmony export EVENT_MANAGER_PLUGINS */
/* unused harmony export EventManager */
/* unused harmony export HAMMER_GESTURE_CONFIG */
/* unused harmony export HammerGestureConfig */
/* unused harmony export DomSanitizer */
/* unused harmony export VERSION */
/* unused harmony export ɵBROWSER_SANITIZATION_PROVIDERS */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return INTERNAL_BROWSER_PLATFORM_PROVIDERS; });
/* unused harmony export ɵinitDomAdapter */
/* unused harmony export ɵBrowserDomAdapter */
/* unused harmony export ɵsetValueOnPath */
/* unused harmony export ɵBrowserPlatformLocation */
/* unused harmony export ɵTRANSITION_ID */
/* unused harmony export ɵBrowserGetTestability */
/* unused harmony export ɵELEMENT_PROBE_PROVIDERS */
/* unused harmony export ɵDomAdapter */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getDOM; });
/* unused harmony export ɵsetRootDomAdapter */
/* unused harmony export ɵDomRendererFactory2 */
/* unused harmony export ɵNAMESPACE_URIS */
/* unused harmony export ɵflattenStyles */
/* unused harmony export ɵshimContentAttribute */
/* unused harmony export ɵshimHostAttribute */
/* unused harmony export ɵDomEventsPlugin */
/* unused harmony export ɵHammerGesturesPlugin */
/* unused harmony export ɵKeyEventsPlugin */
/* unused harmony export ɵDomSharedStylesHost */
/* unused harmony export ɵSharedStylesHost */
/* unused harmony export ɵb */
/* unused harmony export ɵa */
/* unused harmony export ɵh */
/* unused harmony export ɵg */
/* unused harmony export ɵf */
/* unused harmony export ɵc */
/* unused harmony export ɵd */
/* unused harmony export ɵe */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.1
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @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
*/
var _DOM = ((null));
/**
* @return {?}
*/
function getDOM() {
return _DOM;
}
/**
* @param {?} adapter
* @return {?}
*/
/**
* @param {?} adapter
* @return {?}
*/
function setRootDomAdapter(adapter) {
if (!_DOM) {
_DOM = adapter;
}
}
/**
* Provides DOM operations in an environment-agnostic way.
*
* \@security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
* @abstract
*/
var DomAdapter = (function () {
function DomAdapter() {
this.resourceLoaderType = ((null));
}
/**
* @abstract
* @param {?} element
* @param {?} name
* @return {?}
*/
DomAdapter.prototype.hasProperty = function (element, name) { };
/**
* @abstract
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setProperty = function (el, name, value) { };
/**
* @abstract
* @param {?} el
* @param {?} name
* @return {?}
*/
DomAdapter.prototype.getProperty = function (el, name) { };
/**
* @abstract
* @param {?} el
* @param {?} methodName
* @param {?} args
* @return {?}
*/
DomAdapter.prototype.invoke = function (el, methodName, args) { };
/**
* @abstract
* @param {?} error
* @return {?}
*/
DomAdapter.prototype.logError = function (error) { };
/**
* @abstract
* @param {?} error
* @return {?}
*/
DomAdapter.prototype.log = function (error) { };
/**
* @abstract
* @param {?} error
* @return {?}
*/
DomAdapter.prototype.logGroup = function (error) { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.logGroupEnd = function () { };
Object.defineProperty(DomAdapter.prototype, "attrToPropMap", {
/**
* Maps attribute names to their corresponding property names for cases
* where attribute name doesn't match property name.
* @return {?}
*/
get: function () { return this._attrToPropMap; },
/**
* @param {?} value
* @return {?}
*/
set: function (value) { this._attrToPropMap = value; },
enumerable: true,
configurable: true
});
;
;
/**
* @abstract
* @param {?} nodeA
* @param {?} nodeB
* @return {?}
*/
DomAdapter.prototype.contains = function (nodeA, nodeB) { };
/**
* @abstract
* @param {?} templateHtml
* @return {?}
*/
DomAdapter.prototype.parse = function (templateHtml) { };
/**
* @abstract
* @param {?} el
* @param {?} selector
* @return {?}
*/
DomAdapter.prototype.querySelector = function (el, selector) { };
/**
* @abstract
* @param {?} el
* @param {?} selector
* @return {?}
*/
DomAdapter.prototype.querySelectorAll = function (el, selector) { };
/**
* @abstract
* @param {?} el
* @param {?} evt
* @param {?} listener
* @return {?}
*/
DomAdapter.prototype.on = function (el, evt, listener) { };
/**
* @abstract
* @param {?} el
* @param {?} evt
* @param {?} listener
* @return {?}
*/
DomAdapter.prototype.onAndCancel = function (el, evt, listener) { };
/**
* @abstract
* @param {?} el
* @param {?} evt
* @return {?}
*/
DomAdapter.prototype.dispatchEvent = function (el, evt) { };
/**
* @abstract
* @param {?} eventType
* @return {?}
*/
DomAdapter.prototype.createMouseEvent = function (eventType) { };
/**
* @abstract
* @param {?} eventType
* @return {?}
*/
DomAdapter.prototype.createEvent = function (eventType) { };
/**
* @abstract
* @param {?} evt
* @return {?}
*/
DomAdapter.prototype.preventDefault = function (evt) { };
/**
* @abstract
* @param {?} evt
* @return {?}
*/
DomAdapter.prototype.isPrevented = function (evt) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getInnerHTML = function (el) { };
/**
* Returns content if el is a <template> element, null otherwise.
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getTemplateContent = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getOuterHTML = function (el) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.nodeName = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.nodeValue = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.type = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.content = function (node) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.firstChild = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.nextSibling = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.parentElement = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.childNodes = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.childNodesAsList = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.clearNodes = function (el) { };
/**
* @abstract
* @param {?} el
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.appendChild = function (el, node) { };
/**
* @abstract
* @param {?} el
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.removeChild = function (el, node) { };
/**
* @abstract
* @param {?} el
* @param {?} newNode
* @param {?} oldNode
* @return {?}
*/
DomAdapter.prototype.replaceChild = function (el, newNode, oldNode) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.remove = function (el) { };
/**
* @abstract
* @param {?} parent
* @param {?} ref
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.insertBefore = function (parent, ref, node) { };
/**
* @abstract
* @param {?} parent
* @param {?} ref
* @param {?} nodes
* @return {?}
*/
DomAdapter.prototype.insertAllBefore = function (parent, ref, nodes) { };
/**
* @abstract
* @param {?} parent
* @param {?} el
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.insertAfter = function (parent, el, node) { };
/**
* @abstract
* @param {?} el
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setInnerHTML = function (el, value) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getText = function (el) { };
/**
* @abstract
* @param {?} el
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setText = function (el, value) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getValue = function (el) { };
/**
* @abstract
* @param {?} el
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setValue = function (el, value) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getChecked = function (el) { };
/**
* @abstract
* @param {?} el
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setChecked = function (el, value) { };
/**
* @abstract
* @param {?} text
* @return {?}
*/
DomAdapter.prototype.createComment = function (text) { };
/**
* @abstract
* @param {?} html
* @return {?}
*/
DomAdapter.prototype.createTemplate = function (html) { };
/**
* @abstract
* @param {?} tagName
* @param {?=} doc
* @return {?}
*/
DomAdapter.prototype.createElement = function (tagName, doc) { };
/**
* @abstract
* @param {?} ns
* @param {?} tagName
* @param {?=} doc
* @return {?}
*/
DomAdapter.prototype.createElementNS = function (ns, tagName, doc) { };
/**
* @abstract
* @param {?} text
* @param {?=} doc
* @return {?}
*/
DomAdapter.prototype.createTextNode = function (text, doc) { };
/**
* @abstract
* @param {?} attrName
* @param {?} attrValue
* @param {?=} doc
* @return {?}
*/
DomAdapter.prototype.createScriptTag = function (attrName, attrValue, doc) { };
/**
* @abstract
* @param {?} css
* @param {?=} doc
* @return {?}
*/
DomAdapter.prototype.createStyleElement = function (css, doc) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.createShadowRoot = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getShadowRoot = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getHost = function (el) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getDistributedNodes = function (el) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.clone /*<T extends Node>*/ = function (node) { };
/**
* @abstract
* @param {?} element
* @param {?} name
* @return {?}
*/
DomAdapter.prototype.getElementsByClassName = function (element, name) { };
/**
* @abstract
* @param {?} element
* @param {?} name
* @return {?}
*/
DomAdapter.prototype.getElementsByTagName = function (element, name) { };
/**
* @abstract
* @param {?} element
* @return {?}
*/
DomAdapter.prototype.classList = function (element) { };
/**
* @abstract
* @param {?} element
* @param {?} className
* @return {?}
*/
DomAdapter.prototype.addClass = function (element, className) { };
/**
* @abstract
* @param {?} element
* @param {?} className
* @return {?}
*/
DomAdapter.prototype.removeClass = function (element, className) { };
/**
* @abstract
* @param {?} element
* @param {?} className
* @return {?}
*/
DomAdapter.prototype.hasClass = function (element, className) { };
/**
* @abstract
* @param {?} element
* @param {?} styleName
* @param {?} styleValue
* @return {?}
*/
DomAdapter.prototype.setStyle = function (element, styleName, styleValue) { };
/**
* @abstract
* @param {?} element
* @param {?} styleName
* @return {?}
*/
DomAdapter.prototype.removeStyle = function (element, styleName) { };
/**
* @abstract
* @param {?} element
* @param {?} styleName
* @return {?}
*/
DomAdapter.prototype.getStyle = function (element, styleName) { };
/**
* @abstract
* @param {?} element
* @param {?} styleName
* @param {?=} styleValue
* @return {?}
*/
DomAdapter.prototype.hasStyle = function (element, styleName, styleValue) { };
/**
* @abstract
* @param {?} element
* @return {?}
*/
DomAdapter.prototype.tagName = function (element) { };
/**
* @abstract
* @param {?} element
* @return {?}
*/
DomAdapter.prototype.attributeMap = function (element) { };
/**
* @abstract
* @param {?} element
* @param {?} attribute
* @return {?}
*/
DomAdapter.prototype.hasAttribute = function (element, attribute) { };
/**
* @abstract
* @param {?} element
* @param {?} ns
* @param {?} attribute
* @return {?}
*/
DomAdapter.prototype.hasAttributeNS = function (element, ns, attribute) { };
/**
* @abstract
* @param {?} element
* @param {?} attribute
* @return {?}
*/
DomAdapter.prototype.getAttribute = function (element, attribute) { };
/**
* @abstract
* @param {?} element
* @param {?} ns
* @param {?} attribute
* @return {?}
*/
DomAdapter.prototype.getAttributeNS = function (element, ns, attribute) { };
/**
* @abstract
* @param {?} element
* @param {?} name
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setAttribute = function (element, name, value) { };
/**
* @abstract
* @param {?} element
* @param {?} ns
* @param {?} name
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setAttributeNS = function (element, ns, name, value) { };
/**
* @abstract
* @param {?} element
* @param {?} attribute
* @return {?}
*/
DomAdapter.prototype.removeAttribute = function (element, attribute) { };
/**
* @abstract
* @param {?} element
* @param {?} ns
* @param {?} attribute
* @return {?}
*/
DomAdapter.prototype.removeAttributeNS = function (element, ns, attribute) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.templateAwareRoot = function (el) { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.createHtmlDocument = function () { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.getBoundingClientRect = function (el) { };
/**
* @abstract
* @param {?} doc
* @return {?}
*/
DomAdapter.prototype.getTitle = function (doc) { };
/**
* @abstract
* @param {?} doc
* @param {?} newTitle
* @return {?}
*/
DomAdapter.prototype.setTitle = function (doc, newTitle) { };
/**
* @abstract
* @param {?} n
* @param {?} selector
* @return {?}
*/
DomAdapter.prototype.elementMatches = function (n, selector) { };
/**
* @abstract
* @param {?} el
* @return {?}
*/
DomAdapter.prototype.isTemplateElement = function (el) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.isTextNode = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.isCommentNode = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.isElementNode = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.hasShadowRoot = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.isShadowRoot = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.importIntoDoc /*<T extends Node>*/ = function (node) { };
/**
* @abstract
* @param {?} node
* @return {?}
*/
DomAdapter.prototype.adoptNode /*<T extends Node>*/ = function (node) { };
/**
* @abstract
* @param {?} element
* @return {?}
*/
DomAdapter.prototype.getHref = function (element) { };
/**
* @abstract
* @param {?} event
* @return {?}
*/
DomAdapter.prototype.getEventKey = function (event) { };
/**
* @abstract
* @param {?} element
* @param {?} baseUrl
* @param {?} href
* @return {?}
*/
DomAdapter.prototype.resolveAndSetHref = function (element, baseUrl, href) { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.supportsDOMEvents = function () { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.supportsNativeShadowDOM = function () { };
/**
* @abstract
* @param {?} doc
* @param {?} target
* @return {?}
*/
DomAdapter.prototype.getGlobalEventTarget = function (doc, target) { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.getHistory = function () { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.getLocation = function () { };
/**
* @abstract
* @param {?} doc
* @return {?}
*/
DomAdapter.prototype.getBaseHref = function (doc) { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.resetBaseElement = function () { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.getUserAgent = function () { };
/**
* @abstract
* @param {?} element
* @param {?} name
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setData = function (element, name, value) { };
/**
* @abstract
* @param {?} element
* @return {?}
*/
DomAdapter.prototype.getComputedStyle = function (element) { };
/**
* @abstract
* @param {?} element
* @param {?} name
* @return {?}
*/
DomAdapter.prototype.getData = function (element, name) { };
/**
* @abstract
* @param {?} name
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setGlobalVar = function (name, value) { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.supportsWebAnimation = function () { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.performanceNow = function () { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.getAnimationPrefix = function () { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.getTransitionEnd = function () { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.supportsAnimation = function () { };
/**
* @abstract
* @return {?}
*/
DomAdapter.prototype.supportsCookies = function () { };
/**
* @abstract
* @param {?} name
* @return {?}
*/
DomAdapter.prototype.getCookie = function (name) { };
/**
* @abstract
* @param {?} name
* @param {?} value
* @return {?}
*/
DomAdapter.prototype.setCookie = function (name, value) { };
return DomAdapter;
}());
/**
* @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
*/
/**
* Provides DOM operations in any browser environment.
*
* \@security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
* @abstract
*/
var GenericBrowserDomAdapter = (function (_super) {
__extends(GenericBrowserDomAdapter, _super);
function GenericBrowserDomAdapter() {
var _this = _super.call(this) || this;
_this._animationPrefix = null;
_this._transitionEnd = null;
try {
var element_1 = _this.createElement('div', document);
if (_this.getStyle(element_1, 'animationName') != null) {
_this._animationPrefix = '';
}
else {
var domPrefixes = ['Webkit', 'Moz', 'O', 'ms'];
for (var i = 0; i < domPrefixes.length; i++) {
if (_this.getStyle(element_1, domPrefixes[i] + 'AnimationName') != null) {
_this._animationPrefix = '-' + domPrefixes[i].toLowerCase() + '-';
break;
}
}
}
var transEndEventNames_1 = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
Object.keys(transEndEventNames_1).forEach(function (key) {
if (_this.getStyle(element_1, key) != null) {
_this._transitionEnd = transEndEventNames_1[key];
}
});
}
catch (e) {
_this._animationPrefix = null;
_this._transitionEnd = null;
}
return _this;
}
/**
* @param {?} el
* @return {?}
*/
GenericBrowserDomAdapter.prototype.getDistributedNodes = function (el) { return ((el)).getDistributedNodes(); };
/**
* @param {?} el
* @param {?} baseUrl
* @param {?} href
* @return {?}
*/
GenericBrowserDomAdapter.prototype.resolveAndSetHref = function (el, baseUrl, href) {
el.href = href == null ? baseUrl : baseUrl + '/../' + href;
};
/**
* @return {?}
*/
GenericBrowserDomAdapter.prototype.supportsDOMEvents = function () { return true; };
/**
* @return {?}
*/
GenericBrowserDomAdapter.prototype.supportsNativeShadowDOM = function () {
return typeof ((document.body)).createShadowRoot === 'function';
};
/**
* @return {?}
*/
GenericBrowserDomAdapter.prototype.getAnimationPrefix = function () { return this._animationPrefix ? this._animationPrefix : ''; };
/**
* @return {?}
*/
GenericBrowserDomAdapter.prototype.getTransitionEnd = function () { return this._transitionEnd ? this._transitionEnd : ''; };
/**
* @return {?}
*/
GenericBrowserDomAdapter.prototype.supportsAnimation = function () {
return this._animationPrefix != null && this._transitionEnd != null;
};
return GenericBrowserDomAdapter;
}(DomAdapter));
/**
* @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
*/
var _attrToPropMap = {
'class': 'className',
'innerHtml': 'innerHTML',
'readonly': 'readOnly',
'tabindex': 'tabIndex',
};
var DOM_KEY_LOCATION_NUMPAD = 3;
// Map to convert some key or keyIdentifier values to what will be returned by getEventKey
var _keyMap = {
// The following values are here for cross-browser compatibility and to match the W3C standard
// cf http://www.w3.org/TR/DOM-Level-3-Events-key/
'\b': 'Backspace',
'\t': 'Tab',
'\x7F': 'Delete',
'\x1B': 'Escape',
'Del': 'Delete',
'Esc': 'Escape',
'Left': 'ArrowLeft',
'Right': 'ArrowRight',
'Up': 'ArrowUp',
'Down': 'ArrowDown',
'Menu': 'ContextMenu',
'Scroll': 'ScrollLock',
'Win': 'OS'
};
// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
var _chromeNumKeyPadMap = {
'A': '1',
'B': '2',
'C': '3',
'D': '4',
'E': '5',
'F': '6',
'G': '7',
'H': '8',
'I': '9',
'J': '*',
'K': '+',
'M': '-',
'N': '.',
'O': '/',
'\x60': '0',
'\x90': 'NumLock'
};
var nodeContains;
if (__WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['Node']) {
nodeContains = __WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['Node'].prototype.contains || function (node) {
return !!(this.compareDocumentPosition(node) & 16);
};
}
var BrowserDomAdapter = (function (_super) {
__extends(BrowserDomAdapter, _super);
function BrowserDomAdapter() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} templateHtml
* @return {?}
*/
BrowserDomAdapter.prototype.parse = function (templateHtml) { throw new Error('parse not implemented'); };
/**
* @return {?}
*/
BrowserDomAdapter.makeCurrent = function () { setRootDomAdapter(new BrowserDomAdapter()); };
/**
* @param {?} element
* @param {?} name
* @return {?}
*/
BrowserDomAdapter.prototype.hasProperty = function (element, name) { return name in element; };
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setProperty = function (el, name, value) { ((el))[name] = value; };
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
BrowserDomAdapter.prototype.getProperty = function (el, name) { return ((el))[name]; };
/**
* @param {?} el
* @param {?} methodName
* @param {?} args
* @return {?}
*/
BrowserDomAdapter.prototype.invoke = function (el, methodName, args) { ((el))[methodName].apply(((el)), args); };
/**
* @param {?} error
* @return {?}
*/
BrowserDomAdapter.prototype.logError = function (error) {
if (window.console) {
if (console.error) {
console.error(error);
}
else {
console.log(error);
}
}
};
/**
* @param {?} error
* @return {?}
*/
BrowserDomAdapter.prototype.log = function (error) {
if (window.console) {
window.console.log && window.console.log(error);
}
};
/**
* @param {?} error
* @return {?}
*/
BrowserDomAdapter.prototype.logGroup = function (error) {
if (window.console) {
window.console.group && window.console.group(error);
}
};
/**
* @return {?}
*/
BrowserDomAdapter.prototype.logGroupEnd = function () {
if (window.console) {
window.console.groupEnd && window.console.groupEnd();
}
};
Object.defineProperty(BrowserDomAdapter.prototype, "attrToPropMap", {
/**
* @return {?}
*/
get: function () { return _attrToPropMap; },
enumerable: true,
configurable: true
});
/**
* @param {?} nodeA
* @param {?} nodeB
* @return {?}
*/
BrowserDomAdapter.prototype.contains = function (nodeA, nodeB) { return nodeContains.call(nodeA, nodeB); };
/**
* @param {?} el
* @param {?} selector
* @return {?}
*/
BrowserDomAdapter.prototype.querySelector = function (el, selector) { return el.querySelector(selector); };
/**
* @param {?} el
* @param {?} selector
* @return {?}
*/
BrowserDomAdapter.prototype.querySelectorAll = function (el, selector) { return el.querySelectorAll(selector); };
/**
* @param {?} el
* @param {?} evt
* @param {?} listener
* @return {?}
*/
BrowserDomAdapter.prototype.on = function (el, evt, listener) { el.addEventListener(evt, listener, false); };
/**
* @param {?} el
* @param {?} evt
* @param {?} listener
* @return {?}
*/
BrowserDomAdapter.prototype.onAndCancel = function (el, evt, listener) {
el.addEventListener(evt, listener, false);
// Needed to follow Dart's subscription semantic, until fix of
// https://code.google.com/p/dart/issues/detail?id=17406
return function () { el.removeEventListener(evt, listener, false); };
};
/**
* @param {?} el
* @param {?} evt
* @return {?}
*/
BrowserDomAdapter.prototype.dispatchEvent = function (el, evt) { el.dispatchEvent(evt); };
/**
* @param {?} eventType
* @return {?}
*/
BrowserDomAdapter.prototype.createMouseEvent = function (eventType) {
var /** @type {?} */ evt = document.createEvent('MouseEvent');
evt.initEvent(eventType, true, true);
return evt;
};
/**
* @param {?} eventType
* @return {?}
*/
BrowserDomAdapter.prototype.createEvent = function (eventType) {
var /** @type {?} */ evt = document.createEvent('Event');
evt.initEvent(eventType, true, true);
return evt;
};
/**
* @param {?} evt
* @return {?}
*/
BrowserDomAdapter.prototype.preventDefault = function (evt) {
evt.preventDefault();
evt.returnValue = false;
};
/**
* @param {?} evt
* @return {?}
*/
BrowserDomAdapter.prototype.isPrevented = function (evt) {
return evt.defaultPrevented || evt.returnValue != null && !evt.returnValue;
};
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getInnerHTML = function (el) { return el.innerHTML; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getTemplateContent = function (el) {
return 'content' in el && el instanceof HTMLTemplateElement ? el.content : null;
};
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getOuterHTML = function (el) { return el.outerHTML; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.nodeName = function (node) { return node.nodeName; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.nodeValue = function (node) { return node.nodeValue; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.type = function (node) { return node.type; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.content = function (node) {
if (this.hasProperty(node, 'content')) {
return ((node)).content;
}
else {
return node;
}
};
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.firstChild = function (el) { return el.firstChild; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.nextSibling = function (el) { return el.nextSibling; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.parentElement = function (el) { return el.parentNode; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.childNodes = function (el) { return el.childNodes; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.childNodesAsList = function (el) {
var /** @type {?} */ childNodes = el.childNodes;
var /** @type {?} */ res = new Array(childNodes.length);
for (var /** @type {?} */ i = 0; i < childNodes.length; i++) {
res[i] = childNodes[i];
}
return res;
};
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.clearNodes = function (el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
};
/**
* @param {?} el
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.appendChild = function (el, node) { el.appendChild(node); };
/**
* @param {?} el
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.removeChild = function (el, node) { el.removeChild(node); };
/**
* @param {?} el
* @param {?} newChild
* @param {?} oldChild
* @return {?}
*/
BrowserDomAdapter.prototype.replaceChild = function (el, newChild, oldChild) { el.replaceChild(newChild, oldChild); };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.remove = function (node) {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
return node;
};
/**
* @param {?} parent
* @param {?} ref
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.insertBefore = function (parent, ref, node) { parent.insertBefore(node, ref); };
/**
* @param {?} parent
* @param {?} ref
* @param {?} nodes
* @return {?}
*/
BrowserDomAdapter.prototype.insertAllBefore = function (parent, ref, nodes) {
nodes.forEach(function (n) { return parent.insertBefore(n, ref); });
};
/**
* @param {?} parent
* @param {?} ref
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.insertAfter = function (parent, ref, node) { parent.insertBefore(node, ref.nextSibling); };
/**
* @param {?} el
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setInnerHTML = function (el, value) { el.innerHTML = value; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getText = function (el) { return el.textContent; };
/**
* @param {?} el
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setText = function (el, value) { el.textContent = value; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getValue = function (el) { return el.value; };
/**
* @param {?} el
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setValue = function (el, value) { el.value = value; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getChecked = function (el) { return el.checked; };
/**
* @param {?} el
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setChecked = function (el, value) { el.checked = value; };
/**
* @param {?} text
* @return {?}
*/
BrowserDomAdapter.prototype.createComment = function (text) { return document.createComment(text); };
/**
* @param {?} html
* @return {?}
*/
BrowserDomAdapter.prototype.createTemplate = function (html) {
var /** @type {?} */ t = document.createElement('template');
t.innerHTML = html;
return t;
};
/**
* @param {?} tagName
* @param {?=} doc
* @return {?}
*/
BrowserDomAdapter.prototype.createElement = function (tagName, doc) {
if (doc === void 0) { doc = document; }
return doc.createElement(tagName);
};
/**
* @param {?} ns
* @param {?} tagName
* @param {?=} doc
* @return {?}
*/
BrowserDomAdapter.prototype.createElementNS = function (ns, tagName, doc) {
if (doc === void 0) { doc = document; }
return doc.createElementNS(ns, tagName);
};
/**
* @param {?} text
* @param {?=} doc
* @return {?}
*/
BrowserDomAdapter.prototype.createTextNode = function (text, doc) {
if (doc === void 0) { doc = document; }
return doc.createTextNode(text);
};
/**
* @param {?} attrName
* @param {?} attrValue
* @param {?=} doc
* @return {?}
*/
BrowserDomAdapter.prototype.createScriptTag = function (attrName, attrValue, doc) {
if (doc === void 0) { doc = document; }
var /** @type {?} */ el = (doc.createElement('SCRIPT'));
el.setAttribute(attrName, attrValue);
return el;
};
/**
* @param {?} css
* @param {?=} doc
* @return {?}
*/
BrowserDomAdapter.prototype.createStyleElement = function (css, doc) {
if (doc === void 0) { doc = document; }
var /** @type {?} */ style = (doc.createElement('style'));
this.appendChild(style, this.createTextNode(css));
return style;
};
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.createShadowRoot = function (el) { return ((el)).createShadowRoot(); };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getShadowRoot = function (el) { return ((el)).shadowRoot; };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getHost = function (el) { return ((el)).host; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.clone = function (node) { return node.cloneNode(true); };
/**
* @param {?} element
* @param {?} name
* @return {?}
*/
BrowserDomAdapter.prototype.getElementsByClassName = function (element, name) {
return element.getElementsByClassName(name);
};
/**
* @param {?} element
* @param {?} name
* @return {?}
*/
BrowserDomAdapter.prototype.getElementsByTagName = function (element, name) {
return element.getElementsByTagName(name);
};
/**
* @param {?} element
* @return {?}
*/
BrowserDomAdapter.prototype.classList = function (element) { return Array.prototype.slice.call(element.classList, 0); };
/**
* @param {?} element
* @param {?} className
* @return {?}
*/
BrowserDomAdapter.prototype.addClass = function (element, className) { element.classList.add(className); };
/**
* @param {?} element
* @param {?} className
* @return {?}
*/
BrowserDomAdapter.prototype.removeClass = function (element, className) { element.classList.remove(className); };
/**
* @param {?} element
* @param {?} className
* @return {?}
*/
BrowserDomAdapter.prototype.hasClass = function (element, className) {
return element.classList.contains(className);
};
/**
* @param {?} element
* @param {?} styleName
* @param {?} styleValue
* @return {?}
*/
BrowserDomAdapter.prototype.setStyle = function (element, styleName, styleValue) {
element.style[styleName] = styleValue;
};
/**
* @param {?} element
* @param {?} stylename
* @return {?}
*/
BrowserDomAdapter.prototype.removeStyle = function (element, stylename) {
// IE requires '' instead of null
// see https://github.com/angular/angular/issues/7916
element.style[stylename] = '';
};
/**
* @param {?} element
* @param {?} stylename
* @return {?}
*/
BrowserDomAdapter.prototype.getStyle = function (element, stylename) { return element.style[stylename]; };
/**
* @param {?} element
* @param {?} styleName
* @param {?=} styleValue
* @return {?}
*/
BrowserDomAdapter.prototype.hasStyle = function (element, styleName, styleValue) {
var /** @type {?} */ value = this.getStyle(element, styleName) || '';
return styleValue ? value == styleValue : value.length > 0;
};
/**
* @param {?} element
* @return {?}
*/
BrowserDomAdapter.prototype.tagName = function (element) { return element.tagName; };
/**
* @param {?} element
* @return {?}
*/
BrowserDomAdapter.prototype.attributeMap = function (element) {
var /** @type {?} */ res = new Map();
var /** @type {?} */ elAttrs = element.attributes;
for (var /** @type {?} */ i = 0; i < elAttrs.length; i++) {
var /** @type {?} */ attrib = elAttrs[i];
res.set(attrib.name, attrib.value);
}
return res;
};
/**
* @param {?} element
* @param {?} attribute
* @return {?}
*/
BrowserDomAdapter.prototype.hasAttribute = function (element, attribute) {
return element.hasAttribute(attribute);
};
/**
* @param {?} element
* @param {?} ns
* @param {?} attribute
* @return {?}
*/
BrowserDomAdapter.prototype.hasAttributeNS = function (element, ns, attribute) {
return element.hasAttributeNS(ns, attribute);
};
/**
* @param {?} element
* @param {?} attribute
* @return {?}
*/
BrowserDomAdapter.prototype.getAttribute = function (element, attribute) {
return element.getAttribute(attribute);
};
/**
* @param {?} element
* @param {?} ns
* @param {?} name
* @return {?}
*/
BrowserDomAdapter.prototype.getAttributeNS = function (element, ns, name) {
return element.getAttributeNS(ns, name);
};
/**
* @param {?} element
* @param {?} name
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setAttribute = function (element, name, value) { element.setAttribute(name, value); };
/**
* @param {?} element
* @param {?} ns
* @param {?} name
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setAttributeNS = function (element, ns, name, value) {
element.setAttributeNS(ns, name, value);
};
/**
* @param {?} element
* @param {?} attribute
* @return {?}
*/
BrowserDomAdapter.prototype.removeAttribute = function (element, attribute) { element.removeAttribute(attribute); };
/**
* @param {?} element
* @param {?} ns
* @param {?} name
* @return {?}
*/
BrowserDomAdapter.prototype.removeAttributeNS = function (element, ns, name) {
element.removeAttributeNS(ns, name);
};
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.templateAwareRoot = function (el) { return this.isTemplateElement(el) ? this.content(el) : el; };
/**
* @return {?}
*/
BrowserDomAdapter.prototype.createHtmlDocument = function () {
return document.implementation.createHTMLDocument('fakeTitle');
};
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getBoundingClientRect = function (el) {
try {
return el.getBoundingClientRect();
}
catch (e) {
return { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 };
}
};
/**
* @param {?} doc
* @return {?}
*/
BrowserDomAdapter.prototype.getTitle = function (doc) { return document.title; };
/**
* @param {?} doc
* @param {?} newTitle
* @return {?}
*/
BrowserDomAdapter.prototype.setTitle = function (doc, newTitle) { document.title = newTitle || ''; };
/**
* @param {?} n
* @param {?} selector
* @return {?}
*/
BrowserDomAdapter.prototype.elementMatches = function (n, selector) {
if (n instanceof HTMLElement) {
return n.matches && n.matches(selector) ||
n.msMatchesSelector && n.msMatchesSelector(selector) ||
n.webkitMatchesSelector && n.webkitMatchesSelector(selector);
}
return false;
};
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.isTemplateElement = function (el) {
return el instanceof HTMLElement && el.nodeName == 'TEMPLATE';
};
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.isTextNode = function (node) { return node.nodeType === Node.TEXT_NODE; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.isCommentNode = function (node) { return node.nodeType === Node.COMMENT_NODE; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.isElementNode = function (node) { return node.nodeType === Node.ELEMENT_NODE; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.hasShadowRoot = function (node) {
return node.shadowRoot != null && node instanceof HTMLElement;
};
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.isShadowRoot = function (node) { return node instanceof DocumentFragment; };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.importIntoDoc = function (node) { return document.importNode(this.templateAwareRoot(node), true); };
/**
* @param {?} node
* @return {?}
*/
BrowserDomAdapter.prototype.adoptNode = function (node) { return document.adoptNode(node); };
/**
* @param {?} el
* @return {?}
*/
BrowserDomAdapter.prototype.getHref = function (el) { return ((el)).href; };
/**
* @param {?} event
* @return {?}
*/
BrowserDomAdapter.prototype.getEventKey = function (event) {
var /** @type {?} */ key = event.key;
if (key == null) {
key = event.keyIdentifier;
// keyIdentifier is defined in the old draft of DOM Level 3 Events implemented by Chrome and
// Safari cf
// http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/events.html#Events-KeyboardEvents-Interfaces
if (key == null) {
return 'Unidentified';
}
if (key.startsWith('U+')) {
key = String.fromCharCode(parseInt(key.substring(2), 16));
if (event.location === DOM_KEY_LOCATION_NUMPAD && _chromeNumKeyPadMap.hasOwnProperty(key)) {
// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
key = ((_chromeNumKeyPadMap))[key];
}
}
}
return _keyMap[key] || key;
};
/**
* @param {?} doc
* @param {?} target
* @return {?}
*/
BrowserDomAdapter.prototype.getGlobalEventTarget = function (doc, target) {
if (target === 'window') {
return window;
}
if (target === 'document') {
return document;
}
if (target === 'body') {
return document.body;
}
return null;
};
/**
* @return {?}
*/
BrowserDomAdapter.prototype.getHistory = function () { return window.history; };
/**
* @return {?}
*/
BrowserDomAdapter.prototype.getLocation = function () { return window.location; };
/**
* @param {?} doc
* @return {?}
*/
BrowserDomAdapter.prototype.getBaseHref = function (doc) {
var /** @type {?} */ href = getBaseElementHref();
return href == null ? null : relativePath(href);
};
/**
* @return {?}
*/
BrowserDomAdapter.prototype.resetBaseElement = function () { baseElement = null; };
/**
* @return {?}
*/
BrowserDomAdapter.prototype.getUserAgent = function () { return window.navigator.userAgent; };
/**
* @param {?} element
* @param {?} name
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setData = function (element, name, value) {
this.setAttribute(element, 'data-' + name, value);
};
/**
* @param {?} element
* @param {?} name
* @return {?}
*/
BrowserDomAdapter.prototype.getData = function (element, name) {
return this.getAttribute(element, 'data-' + name);
};
/**
* @param {?} element
* @return {?}
*/
BrowserDomAdapter.prototype.getComputedStyle = function (element) { return getComputedStyle(element); };
/**
* @param {?} path
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setGlobalVar = function (path, value) { setValueOnPath(__WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */], path, value); };
/**
* @return {?}
*/
BrowserDomAdapter.prototype.supportsWebAnimation = function () {
return typeof ((Element)).prototype['animate'] === 'function';
};
/**
* @return {?}
*/
BrowserDomAdapter.prototype.performanceNow = function () {
// performance.now() is not available in all browsers, see
// http://caniuse.com/#search=performance.now
return window.performance && window.performance.now ? window.performance.now() :
new Date().getTime();
};
/**
* @return {?}
*/
BrowserDomAdapter.prototype.supportsCookies = function () { return true; };
/**
* @param {?} name
* @return {?}
*/
BrowserDomAdapter.prototype.getCookie = function (name) { return parseCookieValue(document.cookie, name); };
/**
* @param {?} name
* @param {?} value
* @return {?}
*/
BrowserDomAdapter.prototype.setCookie = function (name, value) {
// document.cookie is magical, assigning into it assigns/overrides one cookie value, but does
// not clear other cookies.
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
};
return BrowserDomAdapter;
}(GenericBrowserDomAdapter));
var baseElement = null;
/**
* @return {?}
*/
function getBaseElementHref() {
if (!baseElement) {
baseElement = ((document.querySelector('base')));
if (!baseElement) {
return null;
}
}
return baseElement.getAttribute('href');
}
// based on urlUtils.js in AngularJS 1
var urlParsingNode;
/**
* @param {?} url
* @return {?}
*/
function relativePath(url) {
if (!urlParsingNode) {
urlParsingNode = document.createElement('a');
}
urlParsingNode.setAttribute('href', url);
return (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname :
'/' + urlParsingNode.pathname;
}
/**
* @param {?} cookieStr
* @param {?} name
* @return {?}
*/
function parseCookieValue(cookieStr, name) {
name = encodeURIComponent(name);
for (var _i = 0, _a = cookieStr.split(';'); _i < _a.length; _i++) {
var cookie = _a[_i];
var /** @type {?} */ eqIndex = cookie.indexOf('=');
var _b = eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)], cookieName = _b[0], cookieValue = _b[1];
if (cookieName.trim() === name) {
return decodeURIComponent(cookieValue);
}
}
return null;
}
/**
* @param {?} global
* @param {?} path
* @param {?} value
* @return {?}
*/
function setValueOnPath(global, path, value) {
var /** @type {?} */ parts = path.split('.');
var /** @type {?} */ obj = global;
while (parts.length > 1) {
var /** @type {?} */ name = ((parts.shift()));
if (obj.hasOwnProperty(name) && obj[name] != null) {
obj = obj[name];
}
else {
obj = obj[name] = {};
}
}
if (obj === undefined || obj === null) {
obj = {};
}
obj[((parts.shift()))] = value;
}
/**
* @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
*/
/**
* A DI Token representing the main rendering context. In a browser this is the DOM Document.
*
* Note: Document might not be available in the Application Context when Application and Rendering
* Contexts are not the same (e.g. when running the application into a Web Worker).
*
* \@stable
*/
var DOCUMENT = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["e" /* InjectionToken */]('DocumentToken');
/**
* @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
* @return {?}
*/
function supportsState() {
return !!window.history.pushState;
}
/**
* @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
*/
/**
* `PlatformLocation` encapsulates all of the direct calls to platform APIs.
* This class should not be used directly by an application developer. Instead, use
* {\@link Location}.
*/
var BrowserPlatformLocation = (function (_super) {
__extends(BrowserPlatformLocation, _super);
/**
* @param {?} _doc
*/
function BrowserPlatformLocation(_doc) {
var _this = _super.call(this) || this;
_this._doc = _doc;
_this._init();
return _this;
}
/**
* \@internal
* @return {?}
*/
BrowserPlatformLocation.prototype._init = function () {
this._location = getDOM().getLocation();
this._history = getDOM().getHistory();
};
Object.defineProperty(BrowserPlatformLocation.prototype, "location", {
/**
* @return {?}
*/
get: function () { return this._location; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
BrowserPlatformLocation.prototype.getBaseHrefFromDOM = function () { return ((getDOM().getBaseHref(this._doc))); };
/**
* @param {?} fn
* @return {?}
*/
BrowserPlatformLocation.prototype.onPopState = function (fn) {
getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('popstate', fn, false);
};
/**
* @param {?} fn
* @return {?}
*/
BrowserPlatformLocation.prototype.onHashChange = function (fn) {
getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('hashchange', fn, false);
};
Object.defineProperty(BrowserPlatformLocation.prototype, "pathname", {
/**
* @return {?}
*/
get: function () { return this._location.pathname; },
/**
* @param {?} newPath
* @return {?}
*/
set: function (newPath) { this._location.pathname = newPath; },
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserPlatformLocation.prototype, "search", {
/**
* @return {?}
*/
get: function () { return this._location.search; },
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserPlatformLocation.prototype, "hash", {
/**
* @return {?}
*/
get: function () { return this._location.hash; },
enumerable: true,
configurable: true
});
/**
* @param {?} state
* @param {?} title
* @param {?} url
* @return {?}
*/
BrowserPlatformLocation.prototype.pushState = function (state, title, url) {
if (supportsState()) {
this._history.pushState(state, title, url);
}
else {
this._location.hash = url;
}
};
/**
* @param {?} state
* @param {?} title
* @param {?} url
* @return {?}
*/
BrowserPlatformLocation.prototype.replaceState = function (state, title, url) {
if (supportsState()) {
this._history.replaceState(state, title, url);
}
else {
this._location.hash = url;
}
};
/**
* @return {?}
*/
BrowserPlatformLocation.prototype.forward = function () { this._history.forward(); };
/**
* @return {?}
*/
BrowserPlatformLocation.prototype.back = function () { this._history.back(); };
return BrowserPlatformLocation;
}(__WEBPACK_IMPORTED_MODULE_0__angular_common__["a" /* PlatformLocation */]));
BrowserPlatformLocation.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
BrowserPlatformLocation.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [DOCUMENT,] },] },
]; };
/**
* @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
*/
/**
* A service that can be used to get and add meta tags.
*
* \@experimental
*/
var Meta = (function () {
/**
* @param {?} _doc
*/
function Meta(_doc) {
this._doc = _doc;
this._dom = getDOM();
}
/**
* @param {?} tag
* @param {?=} forceCreation
* @return {?}
*/
Meta.prototype.addTag = function (tag, forceCreation) {
if (forceCreation === void 0) { forceCreation = false; }
if (!tag)
return null;
return this._getOrCreateElement(tag, forceCreation);
};
/**
* @param {?} tags
* @param {?=} forceCreation
* @return {?}
*/
Meta.prototype.addTags = function (tags, forceCreation) {
var _this = this;
if (forceCreation === void 0) { forceCreation = false; }
if (!tags)
return [];
return tags.reduce(function (result, tag) {
if (tag) {
result.push(_this._getOrCreateElement(tag, forceCreation));
}
return result;
}, []);
};
/**
* @param {?} attrSelector
* @return {?}
*/
Meta.prototype.getTag = function (attrSelector) {
if (!attrSelector)
return null;
return this._dom.querySelector(this._doc, "meta[" + attrSelector + "]");
};
/**
* @param {?} attrSelector
* @return {?}
*/
Meta.prototype.getTags = function (attrSelector) {
if (!attrSelector)
return [];
var /** @type {?} */ list /*NodeList*/ = this._dom.querySelectorAll(this._doc, "meta[" + attrSelector + "]");
return list ? [].slice.call(list) : [];
};
/**
* @param {?} tag
* @param {?=} selector
* @return {?}
*/
Meta.prototype.updateTag = function (tag, selector) {
if (!tag)
return null;
selector = selector || this._parseSelector(tag);
var /** @type {?} */ meta = ((this.getTag(selector)));
if (meta) {
return this._setMetaElementAttributes(tag, meta);
}
return this._getOrCreateElement(tag, true);
};
/**
* @param {?} attrSelector
* @return {?}
*/
Meta.prototype.removeTag = function (attrSelector) { this.removeTagElement(/** @type {?} */ ((this.getTag(attrSelector)))); };
/**
* @param {?} meta
* @return {?}
*/
Meta.prototype.removeTagElement = function (meta) {
if (meta) {
this._dom.remove(meta);
}
};
/**
* @param {?} meta
* @param {?=} forceCreation
* @return {?}
*/
Meta.prototype._getOrCreateElement = function (meta, forceCreation) {
if (forceCreation === void 0) { forceCreation = false; }
if (!forceCreation) {
var /** @type {?} */ selector = this._parseSelector(meta);
var /** @type {?} */ elem = ((this.getTag(selector)));
// It's allowed to have multiple elements with the same name so it's not enough to
// just check that element with the same name already present on the page. We also need to
// check if element has tag attributes
if (elem && this._containsAttributes(meta, elem))
return elem;
}
var /** @type {?} */ element = (this._dom.createElement('meta'));
this._setMetaElementAttributes(meta, element);
var /** @type {?} */ head = this._dom.getElementsByTagName(this._doc, 'head')[0];
this._dom.appendChild(head, element);
return element;
};
/**
* @param {?} tag
* @param {?} el
* @return {?}
*/
Meta.prototype._setMetaElementAttributes = function (tag, el) {
var _this = this;
Object.keys(tag).forEach(function (prop) { return _this._dom.setAttribute(el, prop, tag[prop]); });
return el;
};
/**
* @param {?} tag
* @return {?}
*/
Meta.prototype._parseSelector = function (tag) {
var /** @type {?} */ attr = tag.name ? 'name' : 'property';
return attr + "=\"" + tag[attr] + "\"";
};
/**
* @param {?} tag
* @param {?} elem
* @return {?}
*/
Meta.prototype._containsAttributes = function (tag, elem) {
var _this = this;
return Object.keys(tag).every(function (key) { return _this._dom.getAttribute(elem, key) === tag[key]; });
};
return Meta;
}());
Meta.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
Meta.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [DOCUMENT,] },] },
]; };
/**
* @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
*/
/**
* An id that identifies a particular application being bootstrapped, that should
* match across the client/server boundary.
*/
var TRANSITION_ID = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["e" /* InjectionToken */]('TRANSITION_ID');
/**
* @param {?} transitionId
* @param {?} document
* @return {?}
*/
function bootstrapListenerFactory(transitionId, document) {
var /** @type {?} */ factory = function () {
var /** @type {?} */ dom = getDOM();
var /** @type {?} */ styles = Array.prototype.slice.apply(dom.querySelectorAll(document, "style[ng-transition]"));
styles.filter(function (el) { return dom.getAttribute(el, 'ng-transition') === transitionId; })
.forEach(function (el) { return dom.remove(el); });
};
return factory;
}
var SERVER_TRANSITION_PROVIDERS = [
{
provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["w" /* APP_INITIALIZER */],
useFactory: bootstrapListenerFactory,
deps: [TRANSITION_ID, DOCUMENT],
multi: true
},
];
/**
* @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
*/
var BrowserGetTestability = (function () {
function BrowserGetTestability() {
}
/**
* @return {?}
*/
BrowserGetTestability.init = function () { __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["x" /* setTestabilityGetter */])(new BrowserGetTestability()); };
/**
* @param {?} registry
* @return {?}
*/
BrowserGetTestability.prototype.addToWindow = function (registry) {
__WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['getAngularTestability'] = function (elem, findInAncestors) {
if (findInAncestors === void 0) { findInAncestors = true; }
var /** @type {?} */ testability = registry.findTestabilityInTree(elem, findInAncestors);
if (testability == null) {
throw new Error('Could not find testability for element.');
}
return testability;
};
__WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['getAllAngularTestabilities'] = function () { return registry.getAllTestabilities(); };
__WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['getAllAngularRootElements'] = function () { return registry.getAllRootElements(); };
var /** @type {?} */ whenAllStable = function (callback /** TODO #9100 */) {
var /** @type {?} */ testabilities = __WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['getAllAngularTestabilities']();
var /** @type {?} */ count = testabilities.length;
var /** @type {?} */ didWork = false;
var /** @type {?} */ decrement = function (didWork_ /** TODO #9100 */) {
didWork = didWork || didWork_;
count--;
if (count == 0) {
callback(didWork);
}
};
testabilities.forEach(function (testability /** TODO #9100 */) {
testability.whenStable(decrement);
});
};
if (!__WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['frameworkStabilizers']) {
__WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['frameworkStabilizers'] = [];
}
__WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */]['frameworkStabilizers'].push(whenAllStable);
};
/**
* @param {?} registry
* @param {?} elem
* @param {?} findInAncestors
* @return {?}
*/
BrowserGetTestability.prototype.findTestabilityInTree = function (registry, elem, findInAncestors) {
if (elem == null) {
return null;
}
var /** @type {?} */ t = registry.getTestability(elem);
if (t != null) {
return t;
}
else if (!findInAncestors) {
return null;
}
if (getDOM().isShadowRoot(elem)) {
return this.findTestabilityInTree(registry, getDOM().getHost(elem), true);
}
return this.findTestabilityInTree(registry, getDOM().parentElement(elem), true);
};
return BrowserGetTestability;
}());
/**
* @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
*/
/**
* A service that can be used to get and set the title of a current HTML document.
*
* Since an Angular application can't be bootstrapped on the entire HTML document (`<html>` tag)
* it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
* (representing the `<title>` tag). Instead, this service can be used to set and get the current
* title value.
*
* \@experimental
*/
var Title = (function () {
/**
* @param {?} _doc
*/
function Title(_doc) {
this._doc = _doc;
}
/**
* Get the title of the current HTML document.
* @return {?}
*/
Title.prototype.getTitle = function () { return getDOM().getTitle(this._doc); };
/**
* Set the title of the current HTML document.
* @param {?} newTitle
* @return {?}
*/
Title.prototype.setTitle = function (newTitle) { getDOM().setTitle(this._doc, newTitle); };
return Title;
}());
Title.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
Title.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [DOCUMENT,] },] },
]; };
/**
* @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
*/
var __assign = (undefined && undefined.__assign) || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var CORE_TOKENS = {
'ApplicationRef': __WEBPACK_IMPORTED_MODULE_1__angular_core__["y" /* ApplicationRef */],
'NgZone': __WEBPACK_IMPORTED_MODULE_1__angular_core__["z" /* NgZone */],
};
var INSPECT_GLOBAL_NAME = 'ng.probe';
var CORE_TOKENS_GLOBAL_NAME = 'ng.coreTokens';
/**
* Returns a {\@link DebugElement} for the given native DOM element, or
* null if the given native element does not have an Angular view associated
* with it.
* @param {?} element
* @return {?}
*/
function inspectNativeElement(element) {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["A" /* getDebugNode */])(element);
}
/**
* Deprecated. Use the one from '\@angular/core'.
* @deprecated
*/
var NgProbeToken$1 = (function () {
/**
* @param {?} name
* @param {?} token
*/
function NgProbeToken$1(name, token) {
this.name = name;
this.token = token;
}
return NgProbeToken$1;
}());
/**
* @param {?} extraTokens
* @param {?} coreTokens
* @return {?}
*/
function _createNgProbe(extraTokens, coreTokens) {
var /** @type {?} */ tokens = (extraTokens || []).concat(coreTokens || []);
getDOM().setGlobalVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
getDOM().setGlobalVar(CORE_TOKENS_GLOBAL_NAME, __assign({}, CORE_TOKENS, _ngProbeTokensToMap(tokens || [])));
return function () { return inspectNativeElement; };
}
/**
* @param {?} tokens
* @return {?}
*/
function _ngProbeTokensToMap(tokens) {
return tokens.reduce(function (prev, t) { return (prev[t.name] = t.token, prev); }, {});
}
/**
* Providers which support debugging Angular applications (e.g. via `ng.probe`).
*/
var ELEMENT_PROBE_PROVIDERS = [
{
provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["w" /* APP_INITIALIZER */],
useFactory: _createNgProbe,
deps: [
[NgProbeToken$1, new __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */]()],
[__WEBPACK_IMPORTED_MODULE_1__angular_core__["B" /* NgProbeToken */], new __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */]()],
],
multi: true,
},
];
/**
* @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
*/
/**
* \@stable
*/
var EVENT_MANAGER_PLUGINS = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["e" /* InjectionToken */]('EventManagerPlugins');
/**
* \@stable
*/
var EventManager = (function () {
/**
* @param {?} plugins
* @param {?} _zone
*/
function EventManager(plugins, _zone) {
var _this = this;
this._zone = _zone;
this._eventNameToPlugin = new Map();
plugins.forEach(function (p) { return p.manager = _this; });
this._plugins = plugins.slice().reverse();
}
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
EventManager.prototype.addEventListener = function (element, eventName, handler) {
var /** @type {?} */ plugin = this._findPluginFor(eventName);
return plugin.addEventListener(element, eventName, handler);
};
/**
* @param {?} target
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
EventManager.prototype.addGlobalEventListener = function (target, eventName, handler) {
var /** @type {?} */ plugin = this._findPluginFor(eventName);
return plugin.addGlobalEventListener(target, eventName, handler);
};
/**
* @return {?}
*/
EventManager.prototype.getZone = function () { return this._zone; };
/**
* \@internal
* @param {?} eventName
* @return {?}
*/
EventManager.prototype._findPluginFor = function (eventName) {
var /** @type {?} */ plugin = this._eventNameToPlugin.get(eventName);
if (plugin) {
return plugin;
}
var /** @type {?} */ plugins = this._plugins;
for (var /** @type {?} */ i = 0; i < plugins.length; i++) {
var /** @type {?} */ plugin_1 = plugins[i];
if (plugin_1.supports(eventName)) {
this._eventNameToPlugin.set(eventName, plugin_1);
return plugin_1;
}
}
throw new Error("No event manager plugin found for event " + eventName);
};
return EventManager;
}());
EventManager.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
EventManager.ctorParameters = function () { return [
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [EVENT_MANAGER_PLUGINS,] },] },
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["z" /* NgZone */], },
]; };
/**
* @abstract
*/
var EventManagerPlugin = (function () {
/**
* @param {?} _doc
*/
function EventManagerPlugin(_doc) {
this._doc = _doc;
}
/**
* @abstract
* @param {?} eventName
* @return {?}
*/
EventManagerPlugin.prototype.supports = function (eventName) { };
/**
* @abstract
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
EventManagerPlugin.prototype.addEventListener = function (element, eventName, handler) { };
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
EventManagerPlugin.prototype.addGlobalEventListener = function (element, eventName, handler) {
var /** @type {?} */ target = getDOM().getGlobalEventTarget(this._doc, element);
if (!target) {
throw new Error("Unsupported event target " + target + " for event " + eventName);
}
return this.addEventListener(target, eventName, handler);
};
;
return EventManagerPlugin;
}());
/**
* @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
*/
var SharedStylesHost = (function () {
function SharedStylesHost() {
/**
* \@internal
*/
this._stylesSet = new Set();
}
/**
* @param {?} styles
* @return {?}
*/
SharedStylesHost.prototype.addStyles = function (styles) {
var _this = this;
var /** @type {?} */ additions = new Set();
styles.forEach(function (style) {
if (!_this._stylesSet.has(style)) {
_this._stylesSet.add(style);
additions.add(style);
}
});
this.onStylesAdded(additions);
};
/**
* @param {?} additions
* @return {?}
*/
SharedStylesHost.prototype.onStylesAdded = function (additions) { };
/**
* @return {?}
*/
SharedStylesHost.prototype.getAllStyles = function () { return Array.from(this._stylesSet); };
return SharedStylesHost;
}());
SharedStylesHost.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
SharedStylesHost.ctorParameters = function () { return []; };
var DomSharedStylesHost = (function (_super) {
__extends(DomSharedStylesHost, _super);
/**
* @param {?} _doc
*/
function DomSharedStylesHost(_doc) {
var _this = _super.call(this) || this;
_this._doc = _doc;
_this._hostNodes = new Set();
_this._styleNodes = new Set();
_this._hostNodes.add(_doc.head);
return _this;
}
/**
* @param {?} styles
* @param {?} host
* @return {?}
*/
DomSharedStylesHost.prototype._addStylesToHost = function (styles, host) {
var _this = this;
styles.forEach(function (style) {
var /** @type {?} */ styleEl = _this._doc.createElement('style');
styleEl.textContent = style;
_this._styleNodes.add(host.appendChild(styleEl));
});
};
/**
* @param {?} hostNode
* @return {?}
*/
DomSharedStylesHost.prototype.addHost = function (hostNode) {
this._addStylesToHost(this._stylesSet, hostNode);
this._hostNodes.add(hostNode);
};
/**
* @param {?} hostNode
* @return {?}
*/
DomSharedStylesHost.prototype.removeHost = function (hostNode) { this._hostNodes.delete(hostNode); };
/**
* @param {?} additions
* @return {?}
*/
DomSharedStylesHost.prototype.onStylesAdded = function (additions) {
var _this = this;
this._hostNodes.forEach(function (hostNode) { return _this._addStylesToHost(additions, hostNode); });
};
/**
* @return {?}
*/
DomSharedStylesHost.prototype.ngOnDestroy = function () { this._styleNodes.forEach(function (styleNode) { return getDOM().remove(styleNode); }); };
return DomSharedStylesHost;
}(SharedStylesHost));
DomSharedStylesHost.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
DomSharedStylesHost.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [DOCUMENT,] },] },
]; };
/**
* @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
*/
var NAMESPACE_URIS = {
'svg': 'http://www.w3.org/2000/svg',
'xhtml': 'http://www.w3.org/1999/xhtml',
'xlink': 'http://www.w3.org/1999/xlink',
'xml': 'http://www.w3.org/XML/1998/namespace',
'xmlns': 'http://www.w3.org/2000/xmlns/',
};
var COMPONENT_REGEX = /%COMP%/g;
var COMPONENT_VARIABLE = '%COMP%';
var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE;
var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE;
/**
* @param {?} componentShortId
* @return {?}
*/
function shimContentAttribute(componentShortId) {
return CONTENT_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
/**
* @param {?} componentShortId
* @return {?}
*/
function shimHostAttribute(componentShortId) {
return HOST_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
/**
* @param {?} compId
* @param {?} styles
* @param {?} target
* @return {?}
*/
function flattenStyles(compId, styles, target) {
for (var /** @type {?} */ i = 0; i < styles.length; i++) {
var /** @type {?} */ style = styles[i];
if (Array.isArray(style)) {
flattenStyles(compId, style, target);
}
else {
style = style.replace(COMPONENT_REGEX, compId);
target.push(style);
}
}
return target;
}
/**
* @param {?} eventHandler
* @return {?}
*/
function decoratePreventDefault(eventHandler) {
return function (event) {
var /** @type {?} */ allowDefaultBehavior = eventHandler(event);
if (allowDefaultBehavior === false) {
// TODO(tbosch): move preventDefault into event plugins...
event.preventDefault();
event.returnValue = false;
}
};
}
var DomRendererFactory2 = (function () {
/**
* @param {?} eventManager
* @param {?} sharedStylesHost
*/
function DomRendererFactory2(eventManager, sharedStylesHost) {
this.eventManager = eventManager;
this.sharedStylesHost = sharedStylesHost;
this.rendererByCompId = new Map();
this.defaultRenderer = new DefaultDomRenderer2(eventManager);
}
;
/**
* @param {?} element
* @param {?} type
* @return {?}
*/
DomRendererFactory2.prototype.createRenderer = function (element, type) {
if (!element || !type) {
return this.defaultRenderer;
}
switch (type.encapsulation) {
case __WEBPACK_IMPORTED_MODULE_1__angular_core__["C" /* ViewEncapsulation */].Emulated: {
var /** @type {?} */ renderer = this.rendererByCompId.get(type.id);
if (!renderer) {
renderer =
new EmulatedEncapsulationDomRenderer2(this.eventManager, this.sharedStylesHost, type);
this.rendererByCompId.set(type.id, renderer);
}
((renderer)).applyToHost(element);
return renderer;
}
case __WEBPACK_IMPORTED_MODULE_1__angular_core__["C" /* ViewEncapsulation */].Native:
return new ShadowDomRenderer(this.eventManager, this.sharedStylesHost, element, type);
default: {
if (!this.rendererByCompId.has(type.id)) {
var /** @type {?} */ styles = flattenStyles(type.id, type.styles, []);
this.sharedStylesHost.addStyles(styles);
this.rendererByCompId.set(type.id, this.defaultRenderer);
}
return this.defaultRenderer;
}
}
};
return DomRendererFactory2;
}());
DomRendererFactory2.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
DomRendererFactory2.ctorParameters = function () { return [
{ type: EventManager, },
{ type: DomSharedStylesHost, },
]; };
var DefaultDomRenderer2 = (function () {
/**
* @param {?} eventManager
*/
function DefaultDomRenderer2(eventManager) {
this.eventManager = eventManager;
this.data = Object.create(null);
}
/**
* @return {?}
*/
DefaultDomRenderer2.prototype.destroy = function () { };
/**
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
DefaultDomRenderer2.prototype.createElement = function (name, namespace) {
if (namespace) {
return document.createElementNS(NAMESPACE_URIS[namespace], name);
}
return document.createElement(name);
};
/**
* @param {?} value
* @return {?}
*/
DefaultDomRenderer2.prototype.createComment = function (value) { return document.createComment(value); };
/**
* @param {?} value
* @return {?}
*/
DefaultDomRenderer2.prototype.createText = function (value) { return document.createTextNode(value); };
/**
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
DefaultDomRenderer2.prototype.appendChild = function (parent, newChild) { parent.appendChild(newChild); };
/**
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
DefaultDomRenderer2.prototype.insertBefore = function (parent, newChild, refChild) {
if (parent) {
parent.insertBefore(newChild, refChild);
}
};
/**
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
DefaultDomRenderer2.prototype.removeChild = function (parent, oldChild) {
if (parent) {
parent.removeChild(oldChild);
}
};
/**
* @param {?} selectorOrNode
* @return {?}
*/
DefaultDomRenderer2.prototype.selectRootElement = function (selectorOrNode) {
var /** @type {?} */ el = typeof selectorOrNode === 'string' ? document.querySelector(selectorOrNode) :
selectorOrNode;
if (!el) {
throw new Error("The selector \"" + selectorOrNode + "\" did not match any elements");
}
el.textContent = '';
return el;
};
/**
* @param {?} node
* @return {?}
*/
DefaultDomRenderer2.prototype.parentNode = function (node) { return node.parentNode; };
/**
* @param {?} node
* @return {?}
*/
DefaultDomRenderer2.prototype.nextSibling = function (node) { return node.nextSibling; };
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @param {?=} namespace
* @return {?}
*/
DefaultDomRenderer2.prototype.setAttribute = function (el, name, value, namespace) {
if (namespace) {
name = namespace + ":" + name;
var /** @type {?} */ namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.setAttributeNS(namespaceUri, name, value);
}
else {
el.setAttribute(name, value);
}
}
else {
el.setAttribute(name, value);
}
};
/**
* @param {?} el
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
DefaultDomRenderer2.prototype.removeAttribute = function (el, name, namespace) {
if (namespace) {
var /** @type {?} */ namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.removeAttributeNS(namespaceUri, name);
}
else {
el.removeAttribute(namespace + ":" + name);
}
}
else {
el.removeAttribute(name);
}
};
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
DefaultDomRenderer2.prototype.addClass = function (el, name) { el.classList.add(name); };
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
DefaultDomRenderer2.prototype.removeClass = function (el, name) { el.classList.remove(name); };
/**
* @param {?} el
* @param {?} style
* @param {?} value
* @param {?} flags
* @return {?}
*/
DefaultDomRenderer2.prototype.setStyle = function (el, style, value, flags) {
if (flags & __WEBPACK_IMPORTED_MODULE_1__angular_core__["D" /* RendererStyleFlags2 */].DashCase) {
el.style.setProperty(style, value, !!(flags & __WEBPACK_IMPORTED_MODULE_1__angular_core__["D" /* RendererStyleFlags2 */].Important) ? 'important' : '');
}
else {
el.style[style] = value;
}
};
/**
* @param {?} el
* @param {?} style
* @param {?} flags
* @return {?}
*/
DefaultDomRenderer2.prototype.removeStyle = function (el, style, flags) {
if (flags & __WEBPACK_IMPORTED_MODULE_1__angular_core__["D" /* RendererStyleFlags2 */].DashCase) {
el.style.removeProperty(style);
}
else {
// IE requires '' instead of null
// see https://github.com/angular/angular/issues/7916
el.style[style] = '';
}
};
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
DefaultDomRenderer2.prototype.setProperty = function (el, name, value) {
checkNoSyntheticProp(name, 'property');
el[name] = value;
};
/**
* @param {?} node
* @param {?} value
* @return {?}
*/
DefaultDomRenderer2.prototype.setValue = function (node, value) { node.nodeValue = value; };
/**
* @param {?} target
* @param {?} event
* @param {?} callback
* @return {?}
*/
DefaultDomRenderer2.prototype.listen = function (target, event, callback) {
checkNoSyntheticProp(event, 'listener');
if (typeof target === 'string') {
return (this.eventManager.addGlobalEventListener(target, event, decoratePreventDefault(callback)));
}
return ((this.eventManager.addEventListener(target, event, decoratePreventDefault(callback))));
};
return DefaultDomRenderer2;
}());
var AT_CHARCODE = '@'.charCodeAt(0);
/**
* @param {?} name
* @param {?} nameKind
* @return {?}
*/
function checkNoSyntheticProp(name, nameKind) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new Error("Found the synthetic " + nameKind + " " + name + ". Please include either \"BrowserAnimationsModule\" or \"NoopAnimationsModule\" in your application.");
}
}
var EmulatedEncapsulationDomRenderer2 = (function (_super) {
__extends(EmulatedEncapsulationDomRenderer2, _super);
/**
* @param {?} eventManager
* @param {?} sharedStylesHost
* @param {?} component
*/
function EmulatedEncapsulationDomRenderer2(eventManager, sharedStylesHost, component) {
var _this = _super.call(this, eventManager) || this;
_this.component = component;
var styles = flattenStyles(component.id, component.styles, []);
sharedStylesHost.addStyles(styles);
_this.contentAttr = shimContentAttribute(component.id);
_this.hostAttr = shimHostAttribute(component.id);
return _this;
}
/**
* @param {?} element
* @return {?}
*/
EmulatedEncapsulationDomRenderer2.prototype.applyToHost = function (element) { _super.prototype.setAttribute.call(this, element, this.hostAttr, ''); };
/**
* @param {?} parent
* @param {?} name
* @return {?}
*/
EmulatedEncapsulationDomRenderer2.prototype.createElement = function (parent, name) {
var /** @type {?} */ el = _super.prototype.createElement.call(this, parent, name);
_super.prototype.setAttribute.call(this, el, this.contentAttr, '');
return el;
};
return EmulatedEncapsulationDomRenderer2;
}(DefaultDomRenderer2));
var ShadowDomRenderer = (function (_super) {
__extends(ShadowDomRenderer, _super);
/**
* @param {?} eventManager
* @param {?} sharedStylesHost
* @param {?} hostEl
* @param {?} component
*/
function ShadowDomRenderer(eventManager, sharedStylesHost, hostEl, component) {
var _this = _super.call(this, eventManager) || this;
_this.sharedStylesHost = sharedStylesHost;
_this.hostEl = hostEl;
_this.component = component;
_this.shadowRoot = hostEl.createShadowRoot();
_this.sharedStylesHost.addHost(_this.shadowRoot);
var styles = flattenStyles(component.id, component.styles, []);
for (var i = 0; i < styles.length; i++) {
var styleEl = document.createElement('style');
styleEl.textContent = styles[i];
_this.shadowRoot.appendChild(styleEl);
}
return _this;
}
/**
* @param {?} node
* @return {?}
*/
ShadowDomRenderer.prototype.nodeOrShadowRoot = function (node) { return node === this.hostEl ? this.shadowRoot : node; };
/**
* @return {?}
*/
ShadowDomRenderer.prototype.destroy = function () { this.sharedStylesHost.removeHost(this.shadowRoot); };
/**
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
ShadowDomRenderer.prototype.appendChild = function (parent, newChild) {
return _super.prototype.appendChild.call(this, this.nodeOrShadowRoot(parent), newChild);
};
/**
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
ShadowDomRenderer.prototype.insertBefore = function (parent, newChild, refChild) {
return _super.prototype.insertBefore.call(this, this.nodeOrShadowRoot(parent), newChild, refChild);
};
/**
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
ShadowDomRenderer.prototype.removeChild = function (parent, oldChild) {
return _super.prototype.removeChild.call(this, this.nodeOrShadowRoot(parent), oldChild);
};
/**
* @param {?} node
* @return {?}
*/
ShadowDomRenderer.prototype.parentNode = function (node) {
return this.nodeOrShadowRoot(_super.prototype.parentNode.call(this, this.nodeOrShadowRoot(node)));
};
return ShadowDomRenderer;
}(DefaultDomRenderer2));
/**
* @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
*/
var DomEventsPlugin = (function (_super) {
__extends(DomEventsPlugin, _super);
/**
* @param {?} doc
*/
function DomEventsPlugin(doc) {
return _super.call(this, doc) || this;
}
/**
* @param {?} eventName
* @return {?}
*/
DomEventsPlugin.prototype.supports = function (eventName) { return true; };
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
DomEventsPlugin.prototype.addEventListener = function (element, eventName, handler) {
element.addEventListener(eventName, /** @type {?} */ (handler), false);
return function () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); };
};
return DomEventsPlugin;
}(EventManagerPlugin));
DomEventsPlugin.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
DomEventsPlugin.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [DOCUMENT,] },] },
]; };
/**
* @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
*/
var EVENT_NAMES = {
// pan
'pan': true,
'panstart': true,
'panmove': true,
'panend': true,
'pancancel': true,
'panleft': true,
'panright': true,
'panup': true,
'pandown': true,
// pinch
'pinch': true,
'pinchstart': true,
'pinchmove': true,
'pinchend': true,
'pinchcancel': true,
'pinchin': true,
'pinchout': true,
// press
'press': true,
'pressup': true,
// rotate
'rotate': true,
'rotatestart': true,
'rotatemove': true,
'rotateend': true,
'rotatecancel': true,
// swipe
'swipe': true,
'swipeleft': true,
'swiperight': true,
'swipeup': true,
'swipedown': true,
// tap
'tap': true,
};
/**
* A DI token that you can use to provide{\@link HammerGestureConfig} to Angular. Use it to configure
* Hammer gestures.
*
* \@experimental
*/
var HAMMER_GESTURE_CONFIG = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["e" /* InjectionToken */]('HammerGestureConfig');
/**
* \@experimental
*/
var HammerGestureConfig = (function () {
function HammerGestureConfig() {
this.events = [];
this.overrides = {};
}
/**
* @param {?} element
* @return {?}
*/
HammerGestureConfig.prototype.buildHammer = function (element) {
var /** @type {?} */ mc = new Hammer(element);
mc.get('pinch').set({ enable: true });
mc.get('rotate').set({ enable: true });
for (var /** @type {?} */ eventName in this.overrides) {
mc.get(eventName).set(this.overrides[eventName]);
}
return mc;
};
return HammerGestureConfig;
}());
HammerGestureConfig.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
HammerGestureConfig.ctorParameters = function () { return []; };
var HammerGesturesPlugin = (function (_super) {
__extends(HammerGesturesPlugin, _super);
/**
* @param {?} doc
* @param {?} _config
*/
function HammerGesturesPlugin(doc, _config) {
var _this = _super.call(this, doc) || this;
_this._config = _config;
return _this;
}
/**
* @param {?} eventName
* @return {?}
*/
HammerGesturesPlugin.prototype.supports = function (eventName) {
if (!EVENT_NAMES.hasOwnProperty(eventName.toLowerCase()) && !this.isCustomEvent(eventName)) {
return false;
}
if (!((window)).Hammer) {
throw new Error("Hammer.js is not loaded, can not bind " + eventName + " event");
}
return true;
};
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
HammerGesturesPlugin.prototype.addEventListener = function (element, eventName, handler) {
var _this = this;
var /** @type {?} */ zone = this.manager.getZone();
eventName = eventName.toLowerCase();
return zone.runOutsideAngular(function () {
// Creating the manager bind events, must be done outside of angular
var /** @type {?} */ mc = _this._config.buildHammer(element);
var /** @type {?} */ callback = function (eventObj) {
zone.runGuarded(function () { handler(eventObj); });
};
mc.on(eventName, callback);
return function () { return mc.off(eventName, callback); };
});
};
/**
* @param {?} eventName
* @return {?}
*/
HammerGesturesPlugin.prototype.isCustomEvent = function (eventName) { return this._config.events.indexOf(eventName) > -1; };
return HammerGesturesPlugin;
}(EventManagerPlugin));
HammerGesturesPlugin.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
HammerGesturesPlugin.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [DOCUMENT,] },] },
{ type: HammerGestureConfig, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [HAMMER_GESTURE_CONFIG,] },] },
]; };
/**
* @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
*/
var MODIFIER_KEYS = ['alt', 'control', 'meta', 'shift'];
var MODIFIER_KEY_GETTERS = {
'alt': function (event) { return event.altKey; },
'control': function (event) { return event.ctrlKey; },
'meta': function (event) { return event.metaKey; },
'shift': function (event) { return event.shiftKey; }
};
/**
* \@experimental
*/
var KeyEventsPlugin = (function (_super) {
__extends(KeyEventsPlugin, _super);
/**
* @param {?} doc
*/
function KeyEventsPlugin(doc) {
return _super.call(this, doc) || this;
}
/**
* @param {?} eventName
* @return {?}
*/
KeyEventsPlugin.prototype.supports = function (eventName) { return KeyEventsPlugin.parseEventName(eventName) != null; };
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
KeyEventsPlugin.prototype.addEventListener = function (element, eventName, handler) {
var /** @type {?} */ parsedEvent = ((KeyEventsPlugin.parseEventName(eventName)));
var /** @type {?} */ outsideHandler = KeyEventsPlugin.eventCallback(parsedEvent['fullKey'], handler, this.manager.getZone());
return this.manager.getZone().runOutsideAngular(function () {
return getDOM().onAndCancel(element, parsedEvent['domEventName'], outsideHandler);
});
};
/**
* @param {?} eventName
* @return {?}
*/
KeyEventsPlugin.parseEventName = function (eventName) {
var /** @type {?} */ parts = eventName.toLowerCase().split('.');
var /** @type {?} */ domEventName = parts.shift();
if ((parts.length === 0) || !(domEventName === 'keydown' || domEventName === 'keyup')) {
return null;
}
var /** @type {?} */ key = KeyEventsPlugin._normalizeKey(/** @type {?} */ ((parts.pop())));
var /** @type {?} */ fullKey = '';
MODIFIER_KEYS.forEach(function (modifierName) {
var /** @type {?} */ index = parts.indexOf(modifierName);
if (index > -1) {
parts.splice(index, 1);
fullKey += modifierName + '.';
}
});
fullKey += key;
if (parts.length != 0 || key.length === 0) {
// returning null instead of throwing to let another plugin process the event
return null;
}
var /** @type {?} */ result = {};
result['domEventName'] = domEventName;
result['fullKey'] = fullKey;
return result;
};
/**
* @param {?} event
* @return {?}
*/
KeyEventsPlugin.getEventFullKey = function (event) {
var /** @type {?} */ fullKey = '';
var /** @type {?} */ key = getDOM().getEventKey(event);
key = key.toLowerCase();
if (key === ' ') {
key = 'space'; // for readability
}
else if (key === '.') {
key = 'dot'; // because '.' is used as a separator in event names
}
MODIFIER_KEYS.forEach(function (modifierName) {
if (modifierName != key) {
var /** @type {?} */ modifierGetter = MODIFIER_KEY_GETTERS[modifierName];
if (modifierGetter(event)) {
fullKey += modifierName + '.';
}
}
});
fullKey += key;
return fullKey;
};
/**
* @param {?} fullKey
* @param {?} handler
* @param {?} zone
* @return {?}
*/
KeyEventsPlugin.eventCallback = function (fullKey, handler, zone) {
return function (event /** TODO #9100 */) {
if (KeyEventsPlugin.getEventFullKey(event) === fullKey) {
zone.runGuarded(function () { return handler(event); });
}
};
};
/**
* \@internal
* @param {?} keyName
* @return {?}
*/
KeyEventsPlugin._normalizeKey = function (keyName) {
// TODO: switch to a Map if the mapping grows too much
switch (keyName) {
case 'esc':
return 'escape';
default:
return keyName;
}
};
return KeyEventsPlugin;
}(EventManagerPlugin));
KeyEventsPlugin.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
KeyEventsPlugin.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [DOCUMENT,] },] },
]; };
/**
* @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
*/
/**
* A pattern that recognizes a commonly useful subset of URLs that are safe.
*
* This regular expression matches a subset of URLs that will not cause script
* execution if used in URL context within a HTML document. Specifically, this
* regular expression matches if (comment from here on and regex copied from
* Soy's EscapingConventions):
* (1) Either a protocol in a whitelist (http, https, mailto or ftp).
* (2) or no protocol. A protocol must be followed by a colon. The below
* allows that by allowing colons only after one of the characters [/?#].
* A colon after a hash (#) must be in the fragment.
* Otherwise, a colon after a (?) must be in a query.
* Otherwise, a colon after a single solidus (/) must be in a path.
* Otherwise, a colon after a double solidus (//) must be in the authority
* (before port).
*
* The pattern disallows &, used in HTML entity declarations before
* one of the characters in [/?#]. This disallows HTML entities used in the
* protocol name, which should never happen, e.g. "h&#116;tp" for "http".
* It also disallows HTML entities in the first path part of a relative path,
* e.g. "foo&lt;bar/baz". Our existing escaping functions should not produce
* that. More importantly, it disallows masking of a colon,
* e.g. "javascript&#58;...".
*
* This regular expression was taken from the Closure sanitization library.
*/
var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi;
/** A pattern that matches safe data URLs. Only matches image, video and audio types. */
var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+\/]+=*$/i;
/**
* @param {?} url
* @return {?}
*/
function sanitizeUrl(url) {
url = String(url);
if (url.match(SAFE_URL_PATTERN) || url.match(DATA_URL_PATTERN))
return url;
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["E" /* isDevMode */])()) {
getDOM().log("WARNING: sanitizing unsafe URL value " + url + " (see http://g.co/ng/security#xss)");
}
return 'unsafe:' + url;
}
/**
* @param {?} srcset
* @return {?}
*/
function sanitizeSrcset(srcset) {
srcset = String(srcset);
return srcset.split(',').map(function (srcset) { return sanitizeUrl(srcset.trim()); }).join(', ');
}
/**
* @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
*/
/** A <body> element that can be safely used to parse untrusted HTML. Lazily initialized below. */
var inertElement = null;
/** Lazily initialized to make sure the DOM adapter gets set before use. */
var DOM = ((null));
/**
* Returns an HTML element that is guaranteed to not execute code when creating elements in it.
* @return {?}
*/
function getInertElement() {
if (inertElement)
return inertElement;
DOM = getDOM();
// Prefer using <template> element if supported.
var /** @type {?} */ templateEl = DOM.createElement('template');
if ('content' in templateEl)
return templateEl;
var /** @type {?} */ doc = DOM.createHtmlDocument();
inertElement = DOM.querySelector(doc, 'body');
if (inertElement == null) {
// usually there should be only one body element in the document, but IE doesn't have any, so we
// need to create one.
var /** @type {?} */ html = DOM.createElement('html', doc);
inertElement = DOM.createElement('body', doc);
DOM.appendChild(html, inertElement);
DOM.appendChild(doc, html);
}
return inertElement;
}
/**
* @param {?} tags
* @return {?}
*/
function tagSet(tags) {
var /** @type {?} */ res = {};
for (var _i = 0, _a = tags.split(','); _i < _a.length; _i++) {
var t = _a[_i];
res[t] = true;
}
return res;
}
/**
* @param {...?} sets
* @return {?}
*/
function merge() {
var sets = [];
for (var _i = 0; _i < arguments.length; _i++) {
sets[_i] = arguments[_i];
}
var /** @type {?} */ res = {};
for (var _a = 0, sets_1 = sets; _a < sets_1.length; _a++) {
var s = sets_1[_a];
for (var /** @type {?} */ v in s) {
if (s.hasOwnProperty(v))
res[v] = true;
}
}
return res;
}
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr');
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr');
var OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt');
var OPTIONAL_END_TAG_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS);
// Safe Block Elements - HTML5
var BLOCK_ELEMENTS = merge(OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet('address,article,' +
'aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
'h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul'));
// Inline Elements - HTML5
var INLINE_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet('a,abbr,acronym,audio,b,' +
'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,' +
'samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video'));
var VALID_ELEMENTS = merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS);
// Attributes that have href and hence need to be sanitized
var URI_ATTRS = tagSet('background,cite,href,itemtype,longdesc,poster,src,xlink:href');
// Attributes that have special href set hence need to be sanitized
var SRCSET_ATTRS = tagSet('srcset');
var HTML_ATTRS = tagSet('abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,' +
'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' +
'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' +
'scope,scrolling,shape,size,sizes,span,srclang,start,summary,tabindex,target,title,translate,type,usemap,' +
'valign,value,vspace,width');
// NB: This currently conciously doesn't support SVG. SVG sanitization has had several security
// issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via
// innerHTML is required, SVG attributes should be added here.
// NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those
// can be sanitized, but they increase security surface area without a legitimate use case, so they
// are left out here.
var VALID_ATTRS = merge(URI_ATTRS, SRCSET_ATTRS, HTML_ATTRS);
/**
* SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe
* attributes.
*/
var SanitizingHtmlSerializer = (function () {
function SanitizingHtmlSerializer() {
this.sanitizedSomething = false;
this.buf = [];
}
/**
* @param {?} el
* @return {?}
*/
SanitizingHtmlSerializer.prototype.sanitizeChildren = function (el) {
// This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters.
// However this code never accesses properties off of `document` before deleting its contents
// again, so it shouldn't be vulnerable to DOM clobbering.
var /** @type {?} */ current = ((el.firstChild));
while (current) {
if (DOM.isElementNode(current)) {
this.startElement(/** @type {?} */ (current));
}
else if (DOM.isTextNode(current)) {
this.chars(/** @type {?} */ ((DOM.nodeValue(current))));
}
else {
// Strip non-element, non-text nodes.
this.sanitizedSomething = true;
}
if (DOM.firstChild(current)) {
current = ((DOM.firstChild(current)));
continue;
}
while (current) {
// Leaving the element. Walk up and to the right, closing tags as we go.
if (DOM.isElementNode(current)) {
this.endElement(/** @type {?} */ (current));
}
var /** @type {?} */ next = checkClobberedElement(current, /** @type {?} */ ((DOM.nextSibling(current))));
if (next) {
current = next;
break;
}
current = checkClobberedElement(current, /** @type {?} */ ((DOM.parentElement(current))));
}
}
return this.buf.join('');
};
/**
* @param {?} element
* @return {?}
*/
SanitizingHtmlSerializer.prototype.startElement = function (element) {
var _this = this;
var /** @type {?} */ tagName = DOM.nodeName(element).toLowerCase();
if (!VALID_ELEMENTS.hasOwnProperty(tagName)) {
this.sanitizedSomething = true;
return;
}
this.buf.push('<');
this.buf.push(tagName);
DOM.attributeMap(element).forEach(function (value, attrName) {
var /** @type {?} */ lower = attrName.toLowerCase();
if (!VALID_ATTRS.hasOwnProperty(lower)) {
_this.sanitizedSomething = true;
return;
}
// TODO(martinprobst): Special case image URIs for data:image/...
if (URI_ATTRS[lower])
value = sanitizeUrl(value);
if (SRCSET_ATTRS[lower])
value = sanitizeSrcset(value);
_this.buf.push(' ');
_this.buf.push(attrName);
_this.buf.push('="');
_this.buf.push(encodeEntities(value));
_this.buf.push('"');
});
this.buf.push('>');
};
/**
* @param {?} current
* @return {?}
*/
SanitizingHtmlSerializer.prototype.endElement = function (current) {
var /** @type {?} */ tagName = DOM.nodeName(current).toLowerCase();
if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) {
this.buf.push('</');
this.buf.push(tagName);
this.buf.push('>');
}
};
/**
* @param {?} chars
* @return {?}
*/
SanitizingHtmlSerializer.prototype.chars = function (chars) { this.buf.push(encodeEntities(chars)); };
return SanitizingHtmlSerializer;
}());
/**
* @param {?} node
* @param {?} nextNode
* @return {?}
*/
function checkClobberedElement(node, nextNode) {
if (nextNode && DOM.contains(node, nextNode)) {
throw new Error("Failed to sanitize html because the element is clobbered: " + DOM.getOuterHTML(node));
}
return nextNode;
}
// Regular Expressions for parsing tags and attributes
var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// ! to ~ is the ASCII range.
var NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param {?} value
* @return {?}
*/
function encodeEntities(value) {
return value.replace(/&/g, '&amp;')
.replace(SURROGATE_PAIR_REGEXP, function (match) {
var /** @type {?} */ hi = match.charCodeAt(0);
var /** @type {?} */ low = match.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
})
.replace(NON_ALPHANUMERIC_REGEXP, function (match) { return '&#' + match.charCodeAt(0) + ';'; })
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
/**
* When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1'
* attribute to declare ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo').
*
* This is undesirable since we don't want to allow any of these custom attributes. This method
* strips them all.
* @param {?} el
* @return {?}
*/
function stripCustomNsAttrs(el) {
DOM.attributeMap(el).forEach(function (_, attrName) {
if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) {
DOM.removeAttribute(el, attrName);
}
});
for (var _i = 0, _a = DOM.childNodesAsList(el); _i < _a.length; _i++) {
var n = _a[_i];
if (DOM.isElementNode(n))
stripCustomNsAttrs(/** @type {?} */ (n));
}
}
/**
* Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to
* the DOM in a browser environment.
* @param {?} defaultDoc
* @param {?} unsafeHtmlInput
* @return {?}
*/
function sanitizeHtml(defaultDoc, unsafeHtmlInput) {
try {
var /** @type {?} */ containerEl = getInertElement();
// Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).
var /** @type {?} */ unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';
// mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser
// trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.
var /** @type {?} */ mXSSAttempts = 5;
var /** @type {?} */ parsedHtml = unsafeHtml;
do {
if (mXSSAttempts === 0) {
throw new Error('Failed to sanitize html because the input is unstable');
}
mXSSAttempts--;
unsafeHtml = parsedHtml;
DOM.setInnerHTML(containerEl, unsafeHtml);
if (defaultDoc.documentMode) {
// strip custom-namespaced attributes on IE<=11
stripCustomNsAttrs(containerEl);
}
parsedHtml = DOM.getInnerHTML(containerEl);
} while (unsafeHtml !== parsedHtml);
var /** @type {?} */ sanitizer = new SanitizingHtmlSerializer();
var /** @type {?} */ safeHtml = sanitizer.sanitizeChildren(DOM.getTemplateContent(containerEl) || containerEl);
// Clear out the body element.
var /** @type {?} */ parent = DOM.getTemplateContent(containerEl) || containerEl;
for (var _i = 0, _a = DOM.childNodesAsList(parent); _i < _a.length; _i++) {
var child = _a[_i];
DOM.removeChild(parent, child);
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["E" /* isDevMode */])() && sanitizer.sanitizedSomething) {
DOM.log('WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).');
}
return safeHtml;
}
catch (e) {
// In case anything goes wrong, clear out inertElement to reset the entire DOM structure.
inertElement = null;
throw e;
}
}
/**
* @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
*/
/**
* Regular expression for safe style values.
*
* Quotes (" and ') are allowed, but a check must be done elsewhere to ensure they're balanced.
*
* ',' allows multiple values to be assigned to the same property (e.g. background-attachment or
* font-family) and hence could allow multiple values to get injected, but that should pose no risk
* of XSS.
*
* The function expression checks only for XSS safety, not for CSS validity.
*
* This regular expression was taken from the Closure sanitization library, and augmented for
* transformation values.
*/
var VALUES = '[-,."\'%_!# a-zA-Z0-9]+';
var TRANSFORMATION_FNS = '(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|3d)?';
var COLOR_FNS = '(?:rgb|hsl)a?';
var GRADIENTS = '(?:repeating-)?(?:linear|radial)-gradient';
var CSS3_FNS = '(?:calc|attr)';
var FN_ARGS = '\\([-0-9.%, #a-zA-Z]+\\)';
var SAFE_STYLE_VALUE = new RegExp("^(" + VALUES + "|" +
("(?:" + TRANSFORMATION_FNS + "|" + COLOR_FNS + "|" + GRADIENTS + "|" + CSS3_FNS + ")") +
(FN_ARGS + ")$"), 'g');
/**
* Matches a `url(...)` value with an arbitrary argument as long as it does
* not contain parentheses.
*
* The URL value still needs to be sanitized separately.
*
* `url(...)` values are a very common use case, e.g. for `background-image`. With carefully crafted
* CSS style rules, it is possible to construct an information leak with `url` values in CSS, e.g.
* by observing whether scroll bars are displayed, or character ranges used by a font face
* definition.
*
* Angular only allows binding CSS values (as opposed to entire CSS rules), so it is unlikely that
* binding a URL value without further cooperation from the page will cause an information leak, and
* if so, it is just a leak, not a full blown XSS vulnerability.
*
* Given the common use case, low likelihood of attack vector, and low impact of an attack, this
* code is permissive and allows URLs that sanitize otherwise.
*/
var URL_RE = /^url\(([^)]+)\)$/;
/**
* Checks that quotes (" and ') are properly balanced inside a string. Assumes
* that neither escape (\) nor any other character that could result in
* breaking out of a string parsing context are allowed;
* see http://www.w3.org/TR/css3-syntax/#string-token-diagram.
*
* This code was taken from the Closure sanitization library.
* @param {?} value
* @return {?}
*/
function hasBalancedQuotes(value) {
var /** @type {?} */ outsideSingle = true;
var /** @type {?} */ outsideDouble = true;
for (var /** @type {?} */ i = 0; i < value.length; i++) {
var /** @type {?} */ c = value.charAt(i);
if (c === '\'' && outsideDouble) {
outsideSingle = !outsideSingle;
}
else if (c === '"' && outsideSingle) {
outsideDouble = !outsideDouble;
}
}
return outsideSingle && outsideDouble;
}
/**
* Sanitizes the given untrusted CSS style property value (i.e. not an entire object, just a single
* value) and returns a value that is safe to use in a browser environment.
* @param {?} value
* @return {?}
*/
function sanitizeStyle(value) {
value = String(value).trim(); // Make sure it's actually a string.
if (!value)
return '';
// Single url(...) values are supported, but only for URLs that sanitize cleanly. See above for
// reasoning behind this.
var /** @type {?} */ urlMatch = value.match(URL_RE);
if ((urlMatch && sanitizeUrl(urlMatch[1]) === urlMatch[1]) ||
value.match(SAFE_STYLE_VALUE) && hasBalancedQuotes(value)) {
return value; // Safe style values.
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["E" /* isDevMode */])()) {
getDOM().log("WARNING: sanitizing unsafe style value " + value + " (see http://g.co/ng/security#xss).");
}
return 'unsafe';
}
/**
* @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
*/
/**
* DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing
* values to be safe to use in the different DOM contexts.
*
* For example, when binding a URL in an `<a [href]="someValue">` hyperlink, `someValue` will be
* sanitized so that an attacker cannot inject e.g. a `javascript:` URL that would execute code on
* the website.
*
* In specific situations, it might be necessary to disable sanitization, for example if the
* application genuinely needs to produce a `javascript:` style link with a dynamic value in it.
* Users can bypass security by constructing a value with one of the `bypassSecurityTrust...`
* methods, and then binding to that value from the template.
*
* These situations should be very rare, and extraordinary care must be taken to avoid creating a
* Cross Site Scripting (XSS) security bug!
*
* When using `bypassSecurityTrust...`, make sure to call the method as early as possible and as
* close as possible to the source of the value, to make it easy to verify no security bug is
* created by its use.
*
* It is not required (and not recommended) to bypass security if the value is safe, e.g. a URL that
* does not start with a suspicious protocol, or an HTML snippet that does not contain dangerous
* code. The sanitizer leaves safe values intact.
*
* \@security Calling any of the `bypassSecurityTrust...` APIs disables Angular's built-in
* sanitization for the value passed in. Carefully check and audit all values and code paths going
* into this call. Make sure any user data is appropriately escaped for this security context.
* For more detail, see the [Security Guide](http://g.co/ng/security).
*
* \@stable
* @abstract
*/
var DomSanitizer = (function () {
function DomSanitizer() {
}
/**
* Sanitizes a value for use in the given SecurityContext.
*
* If value is trusted for the context, this method will unwrap the contained safe value and use
* it directly. Otherwise, value will be sanitized to be safe in the given context, for example
* by replacing URLs that have an unsafe protocol part (such as `javascript:`). The implementation
* is responsible to make sure that the value can definitely be safely used in the given context.
* @abstract
* @param {?} context
* @param {?} value
* @return {?}
*/
DomSanitizer.prototype.sanitize = function (context, value) { };
/**
* Bypass security and trust the given value to be safe HTML. Only use this when the bound HTML
* is unsafe (e.g. contains `<script>` tags) and the code should be executed. The sanitizer will
* leave safe HTML intact, so in most situations this method should not be used.
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
* @abstract
* @param {?} value
* @return {?}
*/
DomSanitizer.prototype.bypassSecurityTrustHtml = function (value) { };
/**
* Bypass security and trust the given value to be safe style value (CSS).
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
* @abstract
* @param {?} value
* @return {?}
*/
DomSanitizer.prototype.bypassSecurityTrustStyle = function (value) { };
/**
* Bypass security and trust the given value to be safe JavaScript.
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
* @abstract
* @param {?} value
* @return {?}
*/
DomSanitizer.prototype.bypassSecurityTrustScript = function (value) { };
/**
* Bypass security and trust the given value to be a safe style URL, i.e. a value that can be used
* in hyperlinks or `<img src>`.
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
* @abstract
* @param {?} value
* @return {?}
*/
DomSanitizer.prototype.bypassSecurityTrustUrl = function (value) { };
/**
* Bypass security and trust the given value to be a safe resource URL, i.e. a location that may
* be used to load executable code from, like `<script src>`, or `<iframe src>`.
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
* @abstract
* @param {?} value
* @return {?}
*/
DomSanitizer.prototype.bypassSecurityTrustResourceUrl = function (value) { };
return DomSanitizer;
}());
var DomSanitizerImpl = (function (_super) {
__extends(DomSanitizerImpl, _super);
/**
* @param {?} _doc
*/
function DomSanitizerImpl(_doc) {
var _this = _super.call(this) || this;
_this._doc = _doc;
return _this;
}
/**
* @param {?} ctx
* @param {?} value
* @return {?}
*/
DomSanitizerImpl.prototype.sanitize = function (ctx, value) {
if (value == null)
return null;
switch (ctx) {
case __WEBPACK_IMPORTED_MODULE_1__angular_core__["F" /* SecurityContext */].NONE:
return (value);
case __WEBPACK_IMPORTED_MODULE_1__angular_core__["F" /* SecurityContext */].HTML:
if (value instanceof SafeHtmlImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value, 'HTML');
return sanitizeHtml(this._doc, String(value));
case __WEBPACK_IMPORTED_MODULE_1__angular_core__["F" /* SecurityContext */].STYLE:
if (value instanceof SafeStyleImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value, 'Style');
return sanitizeStyle(/** @type {?} */ (value));
case __WEBPACK_IMPORTED_MODULE_1__angular_core__["F" /* SecurityContext */].SCRIPT:
if (value instanceof SafeScriptImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value, 'Script');
throw new Error('unsafe value used in a script context');
case __WEBPACK_IMPORTED_MODULE_1__angular_core__["F" /* SecurityContext */].URL:
if (value instanceof SafeResourceUrlImpl || value instanceof SafeUrlImpl) {
// Allow resource URLs in URL contexts, they are strictly more trusted.
return value.changingThisBreaksApplicationSecurity;
}
this.checkNotSafeValue(value, 'URL');
return sanitizeUrl(String(value));
case __WEBPACK_IMPORTED_MODULE_1__angular_core__["F" /* SecurityContext */].RESOURCE_URL:
if (value instanceof SafeResourceUrlImpl) {
return value.changingThisBreaksApplicationSecurity;
}
this.checkNotSafeValue(value, 'ResourceURL');
throw new Error('unsafe value used in a resource URL context (see http://g.co/ng/security#xss)');
default:
throw new Error("Unexpected SecurityContext " + ctx + " (see http://g.co/ng/security#xss)");
}
};
/**
* @param {?} value
* @param {?} expectedType
* @return {?}
*/
DomSanitizerImpl.prototype.checkNotSafeValue = function (value, expectedType) {
if (value instanceof SafeValueImpl) {
throw new Error("Required a safe " + expectedType + ", got a " + value.getTypeName() + " " +
"(see http://g.co/ng/security#xss)");
}
};
/**
* @param {?} value
* @return {?}
*/
DomSanitizerImpl.prototype.bypassSecurityTrustHtml = function (value) { return new SafeHtmlImpl(value); };
/**
* @param {?} value
* @return {?}
*/
DomSanitizerImpl.prototype.bypassSecurityTrustStyle = function (value) { return new SafeStyleImpl(value); };
/**
* @param {?} value
* @return {?}
*/
DomSanitizerImpl.prototype.bypassSecurityTrustScript = function (value) { return new SafeScriptImpl(value); };
/**
* @param {?} value
* @return {?}
*/
DomSanitizerImpl.prototype.bypassSecurityTrustUrl = function (value) { return new SafeUrlImpl(value); };
/**
* @param {?} value
* @return {?}
*/
DomSanitizerImpl.prototype.bypassSecurityTrustResourceUrl = function (value) {
return new SafeResourceUrlImpl(value);
};
return DomSanitizerImpl;
}(DomSanitizer));
DomSanitizerImpl.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/**
* @nocollapse
*/
DomSanitizerImpl.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["k" /* Inject */], args: [DOCUMENT,] },] },
]; };
/**
* @abstract
*/
var SafeValueImpl = (function () {
/**
* @param {?} changingThisBreaksApplicationSecurity
*/
function SafeValueImpl(changingThisBreaksApplicationSecurity) {
this.changingThisBreaksApplicationSecurity = changingThisBreaksApplicationSecurity;
// empty
}
/**
* @abstract
* @return {?}
*/
SafeValueImpl.prototype.getTypeName = function () { };
/**
* @return {?}
*/
SafeValueImpl.prototype.toString = function () {
return "SafeValue must use [property]=binding: " + this.changingThisBreaksApplicationSecurity +
" (see http://g.co/ng/security#xss)";
};
return SafeValueImpl;
}());
var SafeHtmlImpl = (function (_super) {
__extends(SafeHtmlImpl, _super);
function SafeHtmlImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @return {?}
*/
SafeHtmlImpl.prototype.getTypeName = function () { return 'HTML'; };
return SafeHtmlImpl;
}(SafeValueImpl));
var SafeStyleImpl = (function (_super) {
__extends(SafeStyleImpl, _super);
function SafeStyleImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @return {?}
*/
SafeStyleImpl.prototype.getTypeName = function () { return 'Style'; };
return SafeStyleImpl;
}(SafeValueImpl));
var SafeScriptImpl = (function (_super) {
__extends(SafeScriptImpl, _super);
function SafeScriptImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @return {?}
*/
SafeScriptImpl.prototype.getTypeName = function () { return 'Script'; };
return SafeScriptImpl;
}(SafeValueImpl));
var SafeUrlImpl = (function (_super) {
__extends(SafeUrlImpl, _super);
function SafeUrlImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @return {?}
*/
SafeUrlImpl.prototype.getTypeName = function () { return 'URL'; };
return SafeUrlImpl;
}(SafeValueImpl));
var SafeResourceUrlImpl = (function (_super) {
__extends(SafeResourceUrlImpl, _super);
function SafeResourceUrlImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @return {?}
*/
SafeResourceUrlImpl.prototype.getTypeName = function () { return 'ResourceURL'; };
return SafeResourceUrlImpl;
}(SafeValueImpl));
/**
* @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
*/
var INTERNAL_BROWSER_PLATFORM_PROVIDERS = [
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["G" /* PLATFORM_ID */], useValue: __WEBPACK_IMPORTED_MODULE_0__angular_common__["b" /* ɵPLATFORM_BROWSER_ID */] },
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["H" /* PLATFORM_INITIALIZER */], useValue: initDomAdapter, multi: true },
{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_common__["a" /* PlatformLocation */], useClass: BrowserPlatformLocation },
{ provide: DOCUMENT, useFactory: _document, deps: [] },
];
/**
* \@security Replacing built-in sanitization providers exposes the application to XSS risks.
* Attacker-controlled data introduced by an unsanitized provider could expose your
* application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
* \@experimental
*/
var BROWSER_SANITIZATION_PROVIDERS = [
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["I" /* Sanitizer */], useExisting: DomSanitizer },
{ provide: DomSanitizer, useClass: DomSanitizerImpl },
];
/**
* \@stable
*/
var platformBrowser = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["J" /* createPlatformFactory */])(__WEBPACK_IMPORTED_MODULE_1__angular_core__["K" /* platformCore */], 'browser', INTERNAL_BROWSER_PLATFORM_PROVIDERS);
/**
* @return {?}
*/
function initDomAdapter() {
BrowserDomAdapter.makeCurrent();
BrowserGetTestability.init();
}
/**
* @return {?}
*/
function errorHandler() {
return new __WEBPACK_IMPORTED_MODULE_1__angular_core__["L" /* ErrorHandler */]();
}
/**
* @return {?}
*/
function _document() {
return document;
}
/**
* The ng module for the browser.
*
* \@stable
*/
var BrowserModule = (function () {
/**
* @param {?} parentModule
*/
function BrowserModule(parentModule) {
if (parentModule) {
throw new Error("BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.");
}
}
/**
* Configures a browser-based application to transition from a server-rendered app, if
* one is present on the page. The specified parameters must include an application id,
* which must match between the client and server applications.
*
* \@experimental
* @param {?} params
* @return {?}
*/
BrowserModule.withServerTransition = function (params) {
return {
ngModule: BrowserModule,
providers: [
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["M" /* APP_ID */], useValue: params.appId },
{ provide: TRANSITION_ID, useExisting: __WEBPACK_IMPORTED_MODULE_1__angular_core__["M" /* APP_ID */] },
SERVER_TRANSITION_PROVIDERS,
],
};
};
return BrowserModule;
}());
BrowserModule.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["b" /* NgModule */], args: [{
providers: [
BROWSER_SANITIZATION_PROVIDERS,
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["L" /* ErrorHandler */], useFactory: errorHandler, deps: [] },
{ provide: EVENT_MANAGER_PLUGINS, useClass: DomEventsPlugin, multi: true },
{ provide: EVENT_MANAGER_PLUGINS, useClass: KeyEventsPlugin, multi: true },
{ provide: EVENT_MANAGER_PLUGINS, useClass: HammerGesturesPlugin, multi: true },
{ provide: HAMMER_GESTURE_CONFIG, useClass: HammerGestureConfig },
DomRendererFactory2,
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["N" /* RendererFactory2 */], useExisting: DomRendererFactory2 },
{ provide: SharedStylesHost, useExisting: DomSharedStylesHost },
DomSharedStylesHost,
__WEBPACK_IMPORTED_MODULE_1__angular_core__["O" /* Testability */],
EventManager,
ELEMENT_PROBE_PROVIDERS,
Meta,
Title,
],
exports: [__WEBPACK_IMPORTED_MODULE_0__angular_common__["c" /* CommonModule */], __WEBPACK_IMPORTED_MODULE_1__angular_core__["P" /* ApplicationModule */]]
},] },
];
/**
* @nocollapse
*/
BrowserModule.ctorParameters = function () { return [
{ type: BrowserModule, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["s" /* SkipSelf */] },] },
]; };
/**
* @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
*/
var win = typeof window !== 'undefined' && window || {};
/**
* @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
*/
var ChangeDetectionPerfRecord = (function () {
/**
* @param {?} msPerTick
* @param {?} numTicks
*/
function ChangeDetectionPerfRecord(msPerTick, numTicks) {
this.msPerTick = msPerTick;
this.numTicks = numTicks;
}
return ChangeDetectionPerfRecord;
}());
/**
* Entry point for all Angular profiling-related debug tools. This object
* corresponds to the `ng.profiler` in the dev console.
*/
var AngularProfiler = (function () {
/**
* @param {?} ref
*/
function AngularProfiler(ref) {
this.appRef = ref.injector.get(__WEBPACK_IMPORTED_MODULE_1__angular_core__["y" /* ApplicationRef */]);
}
/**
* Exercises change detection in a loop and then prints the average amount of
* time in milliseconds how long a single round of change detection takes for
* the current state of the UI. It runs a minimum of 5 rounds for a minimum
* of 500 milliseconds.
*
* Optionally, a user may pass a `config` parameter containing a map of
* options. Supported options are:
*
* `record` (boolean) - causes the profiler to record a CPU profile while
* it exercises the change detector. Example:
*
* ```
* ng.profiler.timeChangeDetection({record: true})
* ```
* @param {?} config
* @return {?}
*/
AngularProfiler.prototype.timeChangeDetection = function (config) {
var /** @type {?} */ record = config && config['record'];
var /** @type {?} */ profileName = 'Change Detection';
// Profiler is not available in Android browsers, nor in IE 9 without dev tools opened
var /** @type {?} */ isProfilerAvailable = win.console.profile != null;
if (record && isProfilerAvailable) {
win.console.profile(profileName);
}
var /** @type {?} */ start = getDOM().performanceNow();
var /** @type {?} */ numTicks = 0;
while (numTicks < 5 || (getDOM().performanceNow() - start) < 500) {
this.appRef.tick();
numTicks++;
}
var /** @type {?} */ end = getDOM().performanceNow();
if (record && isProfilerAvailable) {
// need to cast to <any> because type checker thinks there's no argument
// while in fact there is:
//
// https://developer.mozilla.org/en-US/docs/Web/API/Console/profileEnd
((win.console.profileEnd))(profileName);
}
var /** @type {?} */ msPerTick = (end - start) / numTicks;
win.console.log("ran " + numTicks + " change detection cycles");
win.console.log(msPerTick.toFixed(2) + " ms per check");
return new ChangeDetectionPerfRecord(msPerTick, numTicks);
};
return AngularProfiler;
}());
/**
* @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
*/
var PROFILER_GLOBAL_NAME = 'ng.profiler';
/**
* Enabled Angular debug tools that are accessible via your browser's
* developer console.
*
* Usage:
*
* 1. Open developer console (e.g. in Chrome Ctrl + Shift + j)
* 1. Type `ng.` (usually the console will show auto-complete suggestion)
* 1. Try the change detection profiler `ng.profiler.timeChangeDetection()`
* then hit Enter.
*
* \@experimental All debugging apis are currently experimental.
* @template T
* @param {?} ref
* @return {?}
*/
function enableDebugTools(ref) {
getDOM().setGlobalVar(PROFILER_GLOBAL_NAME, new AngularProfiler(ref));
return ref;
}
/**
* Disables Angular tools.
*
* \@experimental All debugging apis are currently experimental.
* @return {?}
*/
function disableDebugTools() {
getDOM().setGlobalVar(PROFILER_GLOBAL_NAME, null);
}
/**
* @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
*/
/**
* Predicates for use with {\@link DebugElement}'s query functions.
*
* \@experimental All debugging apis are currently experimental.
*/
var By = (function () {
function By() {
}
/**
* Match all elements.
*
* ## Example
*
* {\@example platform-browser/dom/debug/ts/by/by.ts region='by_all'}
* @return {?}
*/
By.all = function () { return function (debugElement) { return true; }; };
/**
* Match elements by the given CSS selector.
*
* ## Example
*
* {\@example platform-browser/dom/debug/ts/by/by.ts region='by_css'}
* @param {?} selector
* @return {?}
*/
By.css = function (selector) {
return function (debugElement) {
return debugElement.nativeElement != null ?
getDOM().elementMatches(debugElement.nativeElement, selector) :
false;
};
};
/**
* Match elements that have the given directive present.
*
* ## Example
*
* {\@example platform-browser/dom/debug/ts/by/by.ts region='by_directive'}
* @param {?} type
* @return {?}
*/
By.directive = function (type) {
return function (debugElement) { return ((debugElement.providerTokens)).indexOf(type) !== -1; };
};
return By;
}());
/**
* @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
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
var VERSION = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["u" /* Version */]('4.1.1');
/**
* @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
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the platform-browser package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=platform-browser.es5.js.map
/***/ }),
/* 23 */,
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var OuterSubscriber = (function (_super) {
__extends(OuterSubscriber, _super);
function OuterSubscriber() {
_super.apply(this, arguments);
}
OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.destination.next(innerValue);
};
OuterSubscriber.prototype.notifyError = function (error, innerSub) {
this.destination.error(error);
};
OuterSubscriber.prototype.notifyComplete = function (innerSub) {
this.destination.complete();
};
return OuterSubscriber;
}(Subscriber_1.Subscriber));
exports.OuterSubscriber = OuterSubscriber;
//# sourceMappingURL=OuterSubscriber.js.map
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Observable_1 = __webpack_require__(0);
var Subscriber_1 = __webpack_require__(5);
var Subscription_1 = __webpack_require__(26);
var ObjectUnsubscribedError_1 = __webpack_require__(112);
var SubjectSubscription_1 = __webpack_require__(267);
var rxSubscriber_1 = __webpack_require__(81);
/**
* @class SubjectSubscriber<T>
*/
var SubjectSubscriber = (function (_super) {
__extends(SubjectSubscriber, _super);
function SubjectSubscriber(destination) {
_super.call(this, destination);
this.destination = destination;
}
return SubjectSubscriber;
}(Subscriber_1.Subscriber));
exports.SubjectSubscriber = SubjectSubscriber;
/**
* @class Subject<T>
*/
var Subject = (function (_super) {
__extends(Subject, _super);
function Subject() {
_super.call(this);
this.observers = [];
this.closed = false;
this.isStopped = false;
this.hasError = false;
this.thrownError = null;
}
Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
return new SubjectSubscriber(this);
};
Subject.prototype.lift = function (operator) {
var subject = new AnonymousSubject(this, this);
subject.operator = operator;
return subject;
};
Subject.prototype.next = function (value) {
if (this.closed) {
throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
}
if (!this.isStopped) {
var observers = this.observers;
var len = observers.length;
var copy = observers.slice();
for (var i = 0; i < len; i++) {
copy[i].next(value);
}
}
};
Subject.prototype.error = function (err) {
if (this.closed) {
throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
}
this.hasError = true;
this.thrownError = err;
this.isStopped = true;
var observers = this.observers;
var len = observers.length;
var copy = observers.slice();
for (var i = 0; i < len; i++) {
copy[i].error(err);
}
this.observers.length = 0;
};
Subject.prototype.complete = function () {
if (this.closed) {
throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
}
this.isStopped = true;
var observers = this.observers;
var len = observers.length;
var copy = observers.slice();
for (var i = 0; i < len; i++) {
copy[i].complete();
}
this.observers.length = 0;
};
Subject.prototype.unsubscribe = function () {
this.isStopped = true;
this.closed = true;
this.observers = null;
};
Subject.prototype._trySubscribe = function (subscriber) {
if (this.closed) {
throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
}
else {
return _super.prototype._trySubscribe.call(this, subscriber);
}
};
Subject.prototype._subscribe = function (subscriber) {
if (this.closed) {
throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
}
else if (this.hasError) {
subscriber.error(this.thrownError);
return Subscription_1.Subscription.EMPTY;
}
else if (this.isStopped) {
subscriber.complete();
return Subscription_1.Subscription.EMPTY;
}
else {
this.observers.push(subscriber);
return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
}
};
Subject.prototype.asObservable = function () {
var observable = new Observable_1.Observable();
observable.source = this;
return observable;
};
Subject.create = function (destination, source) {
return new AnonymousSubject(destination, source);
};
return Subject;
}(Observable_1.Observable));
exports.Subject = Subject;
/**
* @class AnonymousSubject<T>
*/
var AnonymousSubject = (function (_super) {
__extends(AnonymousSubject, _super);
function AnonymousSubject(destination, source) {
_super.call(this);
this.destination = destination;
this.source = source;
}
AnonymousSubject.prototype.next = function (value) {
var destination = this.destination;
if (destination && destination.next) {
destination.next(value);
}
};
AnonymousSubject.prototype.error = function (err) {
var destination = this.destination;
if (destination && destination.error) {
this.destination.error(err);
}
};
AnonymousSubject.prototype.complete = function () {
var destination = this.destination;
if (destination && destination.complete) {
this.destination.complete();
}
};
AnonymousSubject.prototype._subscribe = function (subscriber) {
var source = this.source;
if (source) {
return this.source.subscribe(subscriber);
}
else {
return Subscription_1.Subscription.EMPTY;
}
};
return AnonymousSubject;
}(Subject));
exports.AnonymousSubject = AnonymousSubject;
//# sourceMappingURL=Subject.js.map
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isArray_1 = __webpack_require__(47);
var isObject_1 = __webpack_require__(116);
var isFunction_1 = __webpack_require__(83);
var tryCatch_1 = __webpack_require__(49);
var errorObject_1 = __webpack_require__(38);
var UnsubscriptionError_1 = __webpack_require__(326);
/**
* Represents a disposable resource, such as the execution of an Observable. A
* Subscription has one important method, `unsubscribe`, that takes no argument
* and just disposes the resource held by the subscription.
*
* Additionally, subscriptions may be grouped together through the `add()`
* method, which will attach a child Subscription to the current Subscription.
* When a Subscription is unsubscribed, all its children (and its grandchildren)
* will be unsubscribed as well.
*
* @class Subscription
*/
var Subscription = (function () {
/**
* @param {function(): void} [unsubscribe] A function describing how to
* perform the disposal of resources when the `unsubscribe` method is called.
*/
function Subscription(unsubscribe) {
/**
* A flag to indicate whether this Subscription has already been unsubscribed.
* @type {boolean}
*/
this.closed = false;
this._parent = null;
this._parents = null;
this._subscriptions = null;
if (unsubscribe) {
this._unsubscribe = unsubscribe;
}
}
/**
* Disposes the resources held by the subscription. May, for instance, cancel
* an ongoing Observable execution or cancel any other type of work that
* started when the Subscription was created.
* @return {void}
*/
Subscription.prototype.unsubscribe = function () {
var hasErrors = false;
var errors;
if (this.closed) {
return;
}
var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
this.closed = true;
this._parent = null;
this._parents = null;
// null out _subscriptions first so any child subscriptions that attempt
// to remove themselves from this subscription will noop
this._subscriptions = null;
var index = -1;
var len = _parents ? _parents.length : 0;
// if this._parent is null, then so is this._parents, and we
// don't have to remove ourselves from any parent subscriptions.
while (_parent) {
_parent.remove(this);
// if this._parents is null or index >= len,
// then _parent is set to null, and the loop exits
_parent = ++index < len && _parents[index] || null;
}
if (isFunction_1.isFunction(_unsubscribe)) {
var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
if (trial === errorObject_1.errorObject) {
hasErrors = true;
errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
}
}
if (isArray_1.isArray(_subscriptions)) {
index = -1;
len = _subscriptions.length;
while (++index < len) {
var sub = _subscriptions[index];
if (isObject_1.isObject(sub)) {
var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
if (trial === errorObject_1.errorObject) {
hasErrors = true;
errors = errors || [];
var err = errorObject_1.errorObject.e;
if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
}
else {
errors.push(err);
}
}
}
}
}
if (hasErrors) {
throw new UnsubscriptionError_1.UnsubscriptionError(errors);
}
};
/**
* Adds a tear down to be called during the unsubscribe() of this
* Subscription.
*
* If the tear down being added is a subscription that is already
* unsubscribed, is the same reference `add` is being called on, or is
* `Subscription.EMPTY`, it will not be added.
*
* If this subscription is already in an `closed` state, the passed
* tear down logic will be executed immediately.
*
* @param {TeardownLogic} teardown The additional logic to execute on
* teardown.
* @return {Subscription} Returns the Subscription used or created to be
* added to the inner subscriptions list. This Subscription can be used with
* `remove()` to remove the passed teardown logic from the inner subscriptions
* list.
*/
Subscription.prototype.add = function (teardown) {
if (!teardown || (teardown === Subscription.EMPTY)) {
return Subscription.EMPTY;
}
if (teardown === this) {
return this;
}
var subscription = teardown;
switch (typeof teardown) {
case 'function':
subscription = new Subscription(teardown);
case 'object':
if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
return subscription;
}
else if (this.closed) {
subscription.unsubscribe();
return subscription;
}
else if (typeof subscription._addParent !== 'function' /* quack quack */) {
var tmp = subscription;
subscription = new Subscription();
subscription._subscriptions = [tmp];
}
break;
default:
throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
}
var subscriptions = this._subscriptions || (this._subscriptions = []);
subscriptions.push(subscription);
subscription._addParent(this);
return subscription;
};
/**
* Removes a Subscription from the internal list of subscriptions that will
* unsubscribe during the unsubscribe process of this Subscription.
* @param {Subscription} subscription The subscription to remove.
* @return {void}
*/
Subscription.prototype.remove = function (subscription) {
var subscriptions = this._subscriptions;
if (subscriptions) {
var subscriptionIndex = subscriptions.indexOf(subscription);
if (subscriptionIndex !== -1) {
subscriptions.splice(subscriptionIndex, 1);
}
}
};
Subscription.prototype._addParent = function (parent) {
var _a = this, _parent = _a._parent, _parents = _a._parents;
if (!_parent || _parent === parent) {
// If we don't have a parent, or the new parent is the same as the
// current parent, then set this._parent to the new parent.
this._parent = parent;
}
else if (!_parents) {
// If there's already one parent, but not multiple, allocate an Array to
// store the rest of the parent Subscriptions.
this._parents = [parent];
}
else if (_parents.indexOf(parent) === -1) {
// Only add the new parent to the _parents list if it's not already there.
_parents.push(parent);
}
};
Subscription.EMPTY = (function (empty) {
empty.closed = true;
return empty;
}(new Subscription()));
return Subscription;
}());
exports.Subscription = Subscription;
function flattenUnsubscriptionErrors(errors) {
return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
}
//# sourceMappingURL=Subscription.js.map
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var root_1 = __webpack_require__(16);
var isArrayLike_1 = __webpack_require__(113);
var isPromise_1 = __webpack_require__(117);
var isObject_1 = __webpack_require__(116);
var Observable_1 = __webpack_require__(0);
var iterator_1 = __webpack_require__(79);
var InnerSubscriber_1 = __webpack_require__(265);
var observable_1 = __webpack_require__(80);
function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
if (destination.closed) {
return null;
}
if (result instanceof Observable_1.Observable) {
if (result._isScalar) {
destination.next(result.value);
destination.complete();
return null;
}
else {
return result.subscribe(destination);
}
}
else if (isArrayLike_1.isArrayLike(result)) {
for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
destination.next(result[i]);
}
if (!destination.closed) {
destination.complete();
}
}
else if (isPromise_1.isPromise(result)) {
result.then(function (value) {
if (!destination.closed) {
destination.next(value);
destination.complete();
}
}, function (err) { return destination.error(err); })
.then(null, function (err) {
// Escaping the Promise trap: globally throw unhandled errors
root_1.root.setTimeout(function () { throw err; });
});
return destination;
}
else if (result && typeof result[iterator_1.iterator] === 'function') {
var iterator = result[iterator_1.iterator]();
do {
var item = iterator.next();
if (item.done) {
destination.complete();
break;
}
destination.next(item.value);
if (destination.closed) {
break;
}
} while (true);
}
else if (result && typeof result[observable_1.observable] === 'function') {
var obs = result[observable_1.observable]();
if (typeof obs.subscribe !== 'function') {
destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
}
else {
return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
}
}
else {
var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
var msg = ("You provided " + value + " where a stream was expected.")
+ ' You can provide an Observable, Promise, Array, or Iterable.';
destination.error(new TypeError(msg));
}
return null;
}
exports.subscribeToResult = subscribeToResult;
//# sourceMappingURL=subscribeToResult.js.map
/***/ }),
/* 28 */,
/* 29 */,
/* 30 */,
/* 31 */,
/* 32 */,
/* 33 */,
/* 34 */,
/* 35 */,
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subject_1 = __webpack_require__(25);
var ObjectUnsubscribedError_1 = __webpack_require__(112);
/**
* @class BehaviorSubject<T>
*/
var BehaviorSubject = (function (_super) {
__extends(BehaviorSubject, _super);
function BehaviorSubject(_value) {
_super.call(this);
this._value = _value;
}
Object.defineProperty(BehaviorSubject.prototype, "value", {
get: function () {
return this.getValue();
},
enumerable: true,
configurable: true
});
BehaviorSubject.prototype._subscribe = function (subscriber) {
var subscription = _super.prototype._subscribe.call(this, subscriber);
if (subscription && !subscription.closed) {
subscriber.next(this._value);
}
return subscription;
};
BehaviorSubject.prototype.getValue = function () {
if (this.hasError) {
throw this.thrownError;
}
else if (this.closed) {
throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
}
else {
return this._value;
}
};
BehaviorSubject.prototype.next = function (value) {
_super.prototype.next.call(this, this._value = value);
};
return BehaviorSubject;
}(Subject_1.Subject));
exports.BehaviorSubject = BehaviorSubject;
//# sourceMappingURL=BehaviorSubject.js.map
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var AsyncAction_1 = __webpack_require__(323);
var AsyncScheduler_1 = __webpack_require__(324);
/**
*
* Async Scheduler
*
* <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
*
* `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
* event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
* in intervals.
*
* If you just want to "defer" task, that is to perform it right after currently
* executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
* better choice will be the {@link asap} scheduler.
*
* @example <caption>Use async scheduler to delay task</caption>
* const task = () => console.log('it works!');
*
* Rx.Scheduler.async.schedule(task, 2000);
*
* // After 2 seconds logs:
* // "it works!"
*
*
* @example <caption>Use async scheduler to repeat task in intervals</caption>
* function task(state) {
* console.log(state);
* this.schedule(state + 1, 1000); // `this` references currently executing Action,
* // which we reschedule with new state and delay
* }
*
* Rx.Scheduler.async.schedule(task, 3000, 0);
*
* // Logs:
* // 0 after 3s
* // 1 after 4s
* // 2 after 5s
* // 3 after 6s
*
* @static true
* @name async
* @owner Scheduler
*/
exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
//# sourceMappingURL=async.js.map
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// typeof any so that it we don't have to cast when comparing a result to the error object
exports.errorObject = { e: {} };
//# sourceMappingURL=errorObject.js.map
/***/ }),
/* 39 */,
/* 40 */,
/* 41 */,
/* 42 */,
/* 43 */,
/* 44 */,
/* 45 */,
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Observable_1 = __webpack_require__(0);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var EmptyObservable = (function (_super) {
__extends(EmptyObservable, _super);
function EmptyObservable(scheduler) {
_super.call(this);
this.scheduler = scheduler;
}
/**
* Creates an Observable that emits no items to the Observer and immediately
* emits a complete notification.
*
* <span class="informal">Just emits 'complete', and nothing else.
* </span>
*
* <img src="./img/empty.png" width="100%">
*
* This static operator is useful for creating a simple Observable that only
* emits the complete notification. It can be used for composing with other
* Observables, such as in a {@link mergeMap}.
*
* @example <caption>Emit the number 7, then complete.</caption>
* var result = Rx.Observable.empty().startWith(7);
* result.subscribe(x => console.log(x));
*
* @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
* var interval = Rx.Observable.interval(1000);
* var result = interval.mergeMap(x =>
* x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following to the console:
* // x is equal to the count on the interval eg(0,1,2,3,...)
* // x will occur every 1000ms
* // if x % 2 is equal to 1 print abc
* // if x % 2 is not equal to 1 nothing will be output
*
* @see {@link create}
* @see {@link never}
* @see {@link of}
* @see {@link throw}
*
* @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
* the emission of the complete notification.
* @return {Observable} An "empty" Observable: emits only the complete
* notification.
* @static true
* @name empty
* @owner Observable
*/
EmptyObservable.create = function (scheduler) {
return new EmptyObservable(scheduler);
};
EmptyObservable.dispatch = function (arg) {
var subscriber = arg.subscriber;
subscriber.complete();
};
EmptyObservable.prototype._subscribe = function (subscriber) {
var scheduler = this.scheduler;
if (scheduler) {
return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
}
else {
subscriber.complete();
}
};
return EmptyObservable;
}(Observable_1.Observable));
exports.EmptyObservable = EmptyObservable;
//# sourceMappingURL=EmptyObservable.js.map
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
//# sourceMappingURL=isArray.js.map
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function isScheduler(value) {
return value && typeof value.schedule === 'function';
}
exports.isScheduler = isScheduler;
//# sourceMappingURL=isScheduler.js.map
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var errorObject_1 = __webpack_require__(38);
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
}
catch (e) {
errorObject_1.errorObject.e = e;
return errorObject_1.errorObject;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
exports.tryCatch = tryCatch;
;
//# sourceMappingURL=tryCatch.js.map
/***/ }),
/* 50 */,
/* 51 */,
/* 52 */,
/* 53 */,
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(54)
var ieee754 = __webpack_require__(73)
var isArray = __webpack_require__(74)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21)))
/***/ }),
/* 56 */,
/* 57 */,
/* 58 */,
/* 59 */,
/* 60 */,
/* 61 */,
/* 62 */,
/* 63 */,
/* 64 */,
/* 65 */,
/* 66 */,
/* 67 */,
/* 68 */,
/* 69 */,
/* 70 */,
/* 71 */,
/* 72 */,
/* 73 */
/***/ (function(module, exports) {
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
/***/ }),
/* 74 */
/***/ (function(module, exports) {
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Observable_1 = __webpack_require__(0);
var ScalarObservable_1 = __webpack_require__(106);
var EmptyObservable_1 = __webpack_require__(46);
var isScheduler_1 = __webpack_require__(48);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var ArrayObservable = (function (_super) {
__extends(ArrayObservable, _super);
function ArrayObservable(array, scheduler) {
_super.call(this);
this.array = array;
this.scheduler = scheduler;
if (!scheduler && array.length === 1) {
this._isScalar = true;
this.value = array[0];
}
}
ArrayObservable.create = function (array, scheduler) {
return new ArrayObservable(array, scheduler);
};
/**
* Creates an Observable that emits some values you specify as arguments,
* immediately one after the other, and then emits a complete notification.
*
* <span class="informal">Emits the arguments you provide, then completes.
* </span>
*
* <img src="./img/of.png" width="100%">
*
* This static operator is useful for creating a simple Observable that only
* emits the arguments given, and the complete notification thereafter. It can
* be used for composing with other Observables, such as with {@link concat}.
* By default, it uses a `null` IScheduler, which means the `next`
* notifications are sent synchronously, although with a different IScheduler
* it is possible to determine when those notifications will be delivered.
*
* @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
* var numbers = Rx.Observable.of(10, 20, 30);
* var letters = Rx.Observable.of('a', 'b', 'c');
* var interval = Rx.Observable.interval(1000);
* var result = numbers.concat(letters).concat(interval);
* result.subscribe(x => console.log(x));
*
* @see {@link create}
* @see {@link empty}
* @see {@link never}
* @see {@link throw}
*
* @param {...T} values Arguments that represent `next` values to be emitted.
* @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
* the emissions of the `next` notifications.
* @return {Observable<T>} An Observable that emits each given input value.
* @static true
* @name of
* @owner Observable
*/
ArrayObservable.of = function () {
var array = [];
for (var _i = 0; _i < arguments.length; _i++) {
array[_i - 0] = arguments[_i];
}
var scheduler = array[array.length - 1];
if (isScheduler_1.isScheduler(scheduler)) {
array.pop();
}
else {
scheduler = null;
}
var len = array.length;
if (len > 1) {
return new ArrayObservable(array, scheduler);
}
else if (len === 1) {
return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
}
else {
return new EmptyObservable_1.EmptyObservable(scheduler);
}
};
ArrayObservable.dispatch = function (state) {
var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
if (index >= count) {
subscriber.complete();
return;
}
subscriber.next(array[index]);
if (subscriber.closed) {
return;
}
state.index = index + 1;
this.schedule(state);
};
ArrayObservable.prototype._subscribe = function (subscriber) {
var index = 0;
var array = this.array;
var count = array.length;
var scheduler = this.scheduler;
if (scheduler) {
return scheduler.schedule(ArrayObservable.dispatch, 0, {
array: array, index: index, count: count, subscriber: subscriber
});
}
else {
for (var i = 0; i < count && !subscriber.closed; i++) {
subscriber.next(array[i]);
}
subscriber.complete();
}
};
return ArrayObservable;
}(Observable_1.Observable));
exports.ArrayObservable = ArrayObservable;
//# sourceMappingURL=ArrayObservable.js.map
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/**
* Applies a given `project` function to each value emitted by the source
* Observable, and emits the resulting values as an Observable.
*
* <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
* it passes each source value through a transformation function to get
* corresponding output values.</span>
*
* <img src="./img/map.png" width="100%">
*
* Similar to the well known `Array.prototype.map` function, this operator
* applies a projection to each value and emits that projection in the output
* Observable.
*
* @example <caption>Map every click to the clientX position of that click</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var positions = clicks.map(ev => ev.clientX);
* positions.subscribe(x => console.log(x));
*
* @see {@link mapTo}
* @see {@link pluck}
*
* @param {function(value: T, index: number): R} project The function to apply
* to each `value` emitted by the source Observable. The `index` parameter is
* the number `i` for the i-th emission that has happened since the
* subscription, starting from the number `0`.
* @param {any} [thisArg] An optional argument to define what `this` is in the
* `project` function.
* @return {Observable<R>} An Observable that emits the values from the source
* Observable transformed by the given `project` function.
* @method map
* @owner Observable
*/
function map(project, thisArg) {
if (typeof project !== 'function') {
throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
}
return this.lift(new MapOperator(project, thisArg));
}
exports.map = map;
var MapOperator = (function () {
function MapOperator(project, thisArg) {
this.project = project;
this.thisArg = thisArg;
}
MapOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
};
return MapOperator;
}());
exports.MapOperator = MapOperator;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var MapSubscriber = (function (_super) {
__extends(MapSubscriber, _super);
function MapSubscriber(destination, project, thisArg) {
_super.call(this, destination);
this.project = project;
this.count = 0;
this.thisArg = thisArg || this;
}
// NOTE: This looks unoptimized, but it's actually purposefully NOT
// using try/catch optimizations.
MapSubscriber.prototype._next = function (value) {
var result;
try {
result = this.project.call(this.thisArg, value, this.count++);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
};
return MapSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=map.js.map
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var OuterSubscriber_1 = __webpack_require__(24);
var subscribeToResult_1 = __webpack_require__(27);
/**
* Converts a higher-order Observable into a first-order Observable which
* concurrently delivers all values that are emitted on the inner Observables.
*
* <span class="informal">Flattens an Observable-of-Observables.</span>
*
* <img src="./img/mergeAll.png" width="100%">
*
* `mergeAll` subscribes to an Observable that emits Observables, also known as
* a higher-order Observable. Each time it observes one of these emitted inner
* Observables, it subscribes to that and delivers all the values from the
* inner Observable on the output Observable. The output Observable only
* completes once all inner Observables have completed. Any error delivered by
* a inner Observable will be immediately emitted on the output Observable.
*
* @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
* var firstOrder = higherOrder.mergeAll();
* firstOrder.subscribe(x => console.log(x));
*
* @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
* var firstOrder = higherOrder.mergeAll(2);
* firstOrder.subscribe(x => console.log(x));
*
* @see {@link combineAll}
* @see {@link concatAll}
* @see {@link exhaust}
* @see {@link merge}
* @see {@link mergeMap}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
* @see {@link switch}
* @see {@link zipAll}
*
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
* Observables being subscribed to concurrently.
* @return {Observable} An Observable that emits values coming from all the
* inner Observables emitted by the source Observable.
* @method mergeAll
* @owner Observable
*/
function mergeAll(concurrent) {
if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
return this.lift(new MergeAllOperator(concurrent));
}
exports.mergeAll = mergeAll;
var MergeAllOperator = (function () {
function MergeAllOperator(concurrent) {
this.concurrent = concurrent;
}
MergeAllOperator.prototype.call = function (observer, source) {
return source.subscribe(new MergeAllSubscriber(observer, this.concurrent));
};
return MergeAllOperator;
}());
exports.MergeAllOperator = MergeAllOperator;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var MergeAllSubscriber = (function (_super) {
__extends(MergeAllSubscriber, _super);
function MergeAllSubscriber(destination, concurrent) {
_super.call(this, destination);
this.concurrent = concurrent;
this.hasCompleted = false;
this.buffer = [];
this.active = 0;
}
MergeAllSubscriber.prototype._next = function (observable) {
if (this.active < this.concurrent) {
this.active++;
this.add(subscribeToResult_1.subscribeToResult(this, observable));
}
else {
this.buffer.push(observable);
}
};
MergeAllSubscriber.prototype._complete = function () {
this.hasCompleted = true;
if (this.active === 0 && this.buffer.length === 0) {
this.destination.complete();
}
};
MergeAllSubscriber.prototype.notifyComplete = function (innerSub) {
var buffer = this.buffer;
this.remove(innerSub);
this.active--;
if (buffer.length > 0) {
this._next(buffer.shift());
}
else if (this.active === 0 && this.hasCompleted) {
this.destination.complete();
}
};
return MergeAllSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
exports.MergeAllSubscriber = MergeAllSubscriber;
//# sourceMappingURL=mergeAll.js.map
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var subscribeToResult_1 = __webpack_require__(27);
var OuterSubscriber_1 = __webpack_require__(24);
/* tslint:enable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link mergeAll}.</span>
*
* <img src="./img/mergeMap.png" width="100%">
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an Observable, and then merging those resulting Observables and
* emitting the results of this merger.
*
* @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
* var letters = Rx.Observable.of('a', 'b', 'c');
* var result = letters.mergeMap(x =>
* Rx.Observable.interval(1000).map(i => x+i)
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // a0
* // b0
* // c0
* // a1
* // b1
* // c1
* // continues to list a,b,c with respective ascending integers
*
* @see {@link concatMap}
* @see {@link exhaustMap}
* @see {@link merge}
* @see {@link mergeAll}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
* @see {@link switchMap}
*
* @param {function(value: T, ?index: number): ObservableInput} project A function
* that, when applied to an item emitted by the source Observable, returns an
* Observable.
* @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
* A function to produce the value on the output Observable based on the values
* and the indices of the source (outer) emission and the inner Observable
* emission. The arguments passed to this function are:
* - `outerValue`: the value that came from the source
* - `innerValue`: the value that came from the projected Observable
* - `outerIndex`: the "index" of the value that came from the source
* - `innerIndex`: the "index" of the value from the projected Observable
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
* Observables being subscribed to concurrently.
* @return {Observable} An Observable that emits the result of applying the
* projection function (and the optional `resultSelector`) to each item emitted
* by the source Observable and merging the results of the Observables obtained
* from this transformation.
* @method mergeMap
* @owner Observable
*/
function mergeMap(project, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
if (typeof resultSelector === 'number') {
concurrent = resultSelector;
resultSelector = null;
}
return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
}
exports.mergeMap = mergeMap;
var MergeMapOperator = (function () {
function MergeMapOperator(project, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
this.project = project;
this.resultSelector = resultSelector;
this.concurrent = concurrent;
}
MergeMapOperator.prototype.call = function (observer, source) {
return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
};
return MergeMapOperator;
}());
exports.MergeMapOperator = MergeMapOperator;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var MergeMapSubscriber = (function (_super) {
__extends(MergeMapSubscriber, _super);
function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
_super.call(this, destination);
this.project = project;
this.resultSelector = resultSelector;
this.concurrent = concurrent;
this.hasCompleted = false;
this.buffer = [];
this.active = 0;
this.index = 0;
}
MergeMapSubscriber.prototype._next = function (value) {
if (this.active < this.concurrent) {
this._tryNext(value);
}
else {
this.buffer.push(value);
}
};
MergeMapSubscriber.prototype._tryNext = function (value) {
var result;
var index = this.index++;
try {
result = this.project(value, index);
}
catch (err) {
this.destination.error(err);
return;
}
this.active++;
this._innerSub(result, value, index);
};
MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
};
MergeMapSubscriber.prototype._complete = function () {
this.hasCompleted = true;
if (this.active === 0 && this.buffer.length === 0) {
this.destination.complete();
}
};
MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
if (this.resultSelector) {
this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
}
else {
this.destination.next(innerValue);
}
};
MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
var result;
try {
result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
};
MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
var buffer = this.buffer;
this.remove(innerSub);
this.active--;
if (buffer.length > 0) {
this._next(buffer.shift());
}
else if (this.active === 0 && this.hasCompleted) {
this.destination.complete();
}
};
return MergeMapSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
exports.MergeMapSubscriber = MergeMapSubscriber;
//# sourceMappingURL=mergeMap.js.map
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var root_1 = __webpack_require__(16);
function symbolIteratorPonyfill(root) {
var Symbol = root.Symbol;
if (typeof Symbol === 'function') {
if (!Symbol.iterator) {
Symbol.iterator = Symbol('iterator polyfill');
}
return Symbol.iterator;
}
else {
// [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
var Set_1 = root.Set;
if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
return '@@iterator';
}
var Map_1 = root.Map;
// required for compatability with es6-shim
if (Map_1) {
var keys = Object.getOwnPropertyNames(Map_1.prototype);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
// according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
return key;
}
}
}
return '@@iterator';
}
}
exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
exports.iterator = symbolIteratorPonyfill(root_1.root);
/**
* @deprecated use iterator instead
*/
exports.$$iterator = exports.iterator;
//# sourceMappingURL=iterator.js.map
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var root_1 = __webpack_require__(16);
function getSymbolObservable(context) {
var $$observable;
var Symbol = context.Symbol;
if (typeof Symbol === 'function') {
if (Symbol.observable) {
$$observable = Symbol.observable;
}
else {
$$observable = Symbol('observable');
Symbol.observable = $$observable;
}
}
else {
$$observable = '@@observable';
}
return $$observable;
}
exports.getSymbolObservable = getSymbolObservable;
exports.observable = getSymbolObservable(root_1.root);
/**
* @deprecated use observable instead
*/
exports.$$observable = exports.observable;
//# sourceMappingURL=observable.js.map
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var root_1 = __webpack_require__(16);
var Symbol = root_1.root.Symbol;
exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
Symbol.for('rxSubscriber') : '@@rxSubscriber';
/**
* @deprecated use rxSubscriber instead
*/
exports.$$rxSubscriber = exports.rxSubscriber;
//# sourceMappingURL=rxSubscriber.js.map
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* An error thrown when an Observable or a sequence was queried but has no
* elements.
*
* @see {@link first}
* @see {@link last}
* @see {@link single}
*
* @class EmptyError
*/
var EmptyError = (function (_super) {
__extends(EmptyError, _super);
function EmptyError() {
var err = _super.call(this, 'no elements in sequence');
this.name = err.name = 'EmptyError';
this.stack = err.stack;
this.message = err.message;
}
return EmptyError;
}(Error));
exports.EmptyError = EmptyError;
//# sourceMappingURL=EmptyError.js.map
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function isFunction(x) {
return typeof x === 'function';
}
exports.isFunction = isFunction;
//# sourceMappingURL=isFunction.js.map
/***/ }),
/* 84 */,
/* 85 */,
/* 86 */,
/* 87 */,
/* 88 */,
/* 89 */,
/* 90 */,
/* 91 */,
/* 92 */,
/* 93 */,
/* 94 */,
/* 95 */,
/* 96 */,
/* 97 */,
/* 98 */,
/* 99 */,
/* 100 */,
/* 101 */,
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
/**
* Represents a push-based event or value that an {@link Observable} can emit.
* This class is particularly useful for operators that manage notifications,
* like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
* others. Besides wrapping the actual delivered value, it also annotates it
* with metadata of, for instance, what type of push message it is (`next`,
* `error`, or `complete`).
*
* @see {@link materialize}
* @see {@link dematerialize}
* @see {@link observeOn}
*
* @class Notification<T>
*/
var Notification = (function () {
function Notification(kind, value, error) {
this.kind = kind;
this.value = value;
this.error = error;
this.hasValue = kind === 'N';
}
/**
* Delivers to the given `observer` the value wrapped by this Notification.
* @param {Observer} observer
* @return
*/
Notification.prototype.observe = function (observer) {
switch (this.kind) {
case 'N':
return observer.next && observer.next(this.value);
case 'E':
return observer.error && observer.error(this.error);
case 'C':
return observer.complete && observer.complete();
}
};
/**
* Given some {@link Observer} callbacks, deliver the value represented by the
* current Notification to the correctly corresponding callback.
* @param {function(value: T): void} next An Observer `next` callback.
* @param {function(err: any): void} [error] An Observer `error` callback.
* @param {function(): void} [complete] An Observer `complete` callback.
* @return {any}
*/
Notification.prototype.do = function (next, error, complete) {
var kind = this.kind;
switch (kind) {
case 'N':
return next && next(this.value);
case 'E':
return error && error(this.error);
case 'C':
return complete && complete();
}
};
/**
* Takes an Observer or its individual callback functions, and calls `observe`
* or `do` methods accordingly.
* @param {Observer|function(value: T): void} nextOrObserver An Observer or
* the `next` callback.
* @param {function(err: any): void} [error] An Observer `error` callback.
* @param {function(): void} [complete] An Observer `complete` callback.
* @return {any}
*/
Notification.prototype.accept = function (nextOrObserver, error, complete) {
if (nextOrObserver && typeof nextOrObserver.next === 'function') {
return this.observe(nextOrObserver);
}
else {
return this.do(nextOrObserver, error, complete);
}
};
/**
* Returns a simple Observable that just delivers the notification represented
* by this Notification instance.
* @return {any}
*/
Notification.prototype.toObservable = function () {
var kind = this.kind;
switch (kind) {
case 'N':
return Observable_1.Observable.of(this.value);
case 'E':
return Observable_1.Observable.throw(this.error);
case 'C':
return Observable_1.Observable.empty();
}
throw new Error('unexpected notification kind value');
};
/**
* A shortcut to create a Notification instance of the type `next` from a
* given value.
* @param {T} value The `next` value.
* @return {Notification<T>} The "next" Notification representing the
* argument.
*/
Notification.createNext = function (value) {
if (typeof value !== 'undefined') {
return new Notification('N', value);
}
return this.undefinedValueNotification;
};
/**
* A shortcut to create a Notification instance of the type `error` from a
* given error.
* @param {any} [err] The `error` error.
* @return {Notification<T>} The "error" Notification representing the
* argument.
*/
Notification.createError = function (err) {
return new Notification('E', undefined, err);
};
/**
* A shortcut to create a Notification instance of the type `complete`.
* @return {Notification<any>} The valueless "complete" Notification.
*/
Notification.createComplete = function () {
return this.completeNotification;
};
Notification.completeNotification = new Notification('C');
Notification.undefinedValueNotification = new Notification('N', undefined);
return Notification;
}());
exports.Notification = Notification;
//# sourceMappingURL=Notification.js.map
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.empty = {
closed: true,
next: function (value) { },
error: function (err) { throw err; },
complete: function () { }
};
//# sourceMappingURL=Observer.js.map
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var map_1 = __webpack_require__(76);
Observable_1.Observable.prototype.map = map_1.map;
//# sourceMappingURL=map.js.map
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var root_1 = __webpack_require__(16);
var Observable_1 = __webpack_require__(0);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var PromiseObservable = (function (_super) {
__extends(PromiseObservable, _super);
function PromiseObservable(promise, scheduler) {
_super.call(this);
this.promise = promise;
this.scheduler = scheduler;
}
/**
* Converts a Promise to an Observable.
*
* <span class="informal">Returns an Observable that just emits the Promise's
* resolved value, then completes.</span>
*
* Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
* Observable. If the Promise resolves with a value, the output Observable
* emits that resolved value as a `next`, and then completes. If the Promise
* is rejected, then the output Observable emits the corresponding Error.
*
* @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
* var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
* result.subscribe(x => console.log(x), e => console.error(e));
*
* @see {@link bindCallback}
* @see {@link from}
*
* @param {Promise<T>} promise The promise to be converted.
* @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
* the delivery of the resolved value (or the rejection).
* @return {Observable<T>} An Observable which wraps the Promise.
* @static true
* @name fromPromise
* @owner Observable
*/
PromiseObservable.create = function (promise, scheduler) {
return new PromiseObservable(promise, scheduler);
};
PromiseObservable.prototype._subscribe = function (subscriber) {
var _this = this;
var promise = this.promise;
var scheduler = this.scheduler;
if (scheduler == null) {
if (this._isScalar) {
if (!subscriber.closed) {
subscriber.next(this.value);
subscriber.complete();
}
}
else {
promise.then(function (value) {
_this.value = value;
_this._isScalar = true;
if (!subscriber.closed) {
subscriber.next(value);
subscriber.complete();
}
}, function (err) {
if (!subscriber.closed) {
subscriber.error(err);
}
})
.then(null, function (err) {
// escape the promise trap, throw unhandled errors
root_1.root.setTimeout(function () { throw err; });
});
}
}
else {
if (this._isScalar) {
if (!subscriber.closed) {
return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
}
}
else {
promise.then(function (value) {
_this.value = value;
_this._isScalar = true;
if (!subscriber.closed) {
subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
}
}, function (err) {
if (!subscriber.closed) {
subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
}
})
.then(null, function (err) {
// escape the promise trap, throw unhandled errors
root_1.root.setTimeout(function () { throw err; });
});
}
}
};
return PromiseObservable;
}(Observable_1.Observable));
exports.PromiseObservable = PromiseObservable;
function dispatchNext(arg) {
var value = arg.value, subscriber = arg.subscriber;
if (!subscriber.closed) {
subscriber.next(value);
subscriber.complete();
}
}
function dispatchError(arg) {
var err = arg.err, subscriber = arg.subscriber;
if (!subscriber.closed) {
subscriber.error(err);
}
}
//# sourceMappingURL=PromiseObservable.js.map
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Observable_1 = __webpack_require__(0);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var ScalarObservable = (function (_super) {
__extends(ScalarObservable, _super);
function ScalarObservable(value, scheduler) {
_super.call(this);
this.value = value;
this.scheduler = scheduler;
this._isScalar = true;
if (scheduler) {
this._isScalar = false;
}
}
ScalarObservable.create = function (value, scheduler) {
return new ScalarObservable(value, scheduler);
};
ScalarObservable.dispatch = function (state) {
var done = state.done, value = state.value, subscriber = state.subscriber;
if (done) {
subscriber.complete();
return;
}
subscriber.next(value);
if (subscriber.closed) {
return;
}
state.done = true;
this.schedule(state);
};
ScalarObservable.prototype._subscribe = function (subscriber) {
var value = this.value;
var scheduler = this.scheduler;
if (scheduler) {
return scheduler.schedule(ScalarObservable.dispatch, 0, {
done: false, value: value, subscriber: subscriber
});
}
else {
subscriber.next(value);
if (!subscriber.closed) {
subscriber.complete();
}
}
};
return ScalarObservable;
}(Observable_1.Observable));
exports.ScalarObservable = ScalarObservable;
//# sourceMappingURL=ScalarObservable.js.map
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var FromObservable_1 = __webpack_require__(291);
exports.from = FromObservable_1.FromObservable.create;
//# sourceMappingURL=from.js.map
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var PromiseObservable_1 = __webpack_require__(105);
exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
//# sourceMappingURL=fromPromise.js.map
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var merge_1 = __webpack_require__(313);
exports.merge = merge_1.mergeStatic;
//# sourceMappingURL=merge.js.map
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ArrayObservable_1 = __webpack_require__(75);
exports.of = ArrayObservable_1.ArrayObservable.of;
//# sourceMappingURL=of.js.map
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/* tslint:enable:max-line-length */
/**
* Filter items emitted by the source Observable by only emitting those that
* satisfy a specified predicate.
*
* <span class="informal">Like
* [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
* it only emits a value from the source if it passes a criterion function.</span>
*
* <img src="./img/filter.png" width="100%">
*
* Similar to the well-known `Array.prototype.filter` method, this operator
* takes values from the source Observable, passes them through a `predicate`
* function and only emits those values that yielded `true`.
*
* @example <caption>Emit only click events whose target was a DIV element</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
* clicksOnDivs.subscribe(x => console.log(x));
*
* @see {@link distinct}
* @see {@link distinctUntilChanged}
* @see {@link distinctUntilKeyChanged}
* @see {@link ignoreElements}
* @see {@link partition}
* @see {@link skip}
*
* @param {function(value: T, index: number): boolean} predicate A function that
* evaluates each value emitted by the source Observable. If it returns `true`,
* the value is emitted, if `false` the value is not passed to the output
* Observable. The `index` parameter is the number `i` for the i-th source
* emission that has happened since the subscription, starting from the number
* `0`.
* @param {any} [thisArg] An optional argument to determine the value of `this`
* in the `predicate` function.
* @return {Observable} An Observable of values from the source that were
* allowed by the `predicate` function.
* @method filter
* @owner Observable
*/
function filter(predicate, thisArg) {
return this.lift(new FilterOperator(predicate, thisArg));
}
exports.filter = filter;
var FilterOperator = (function () {
function FilterOperator(predicate, thisArg) {
this.predicate = predicate;
this.thisArg = thisArg;
}
FilterOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
};
return FilterOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var FilterSubscriber = (function (_super) {
__extends(FilterSubscriber, _super);
function FilterSubscriber(destination, predicate, thisArg) {
_super.call(this, destination);
this.predicate = predicate;
this.thisArg = thisArg;
this.count = 0;
this.predicate = predicate;
}
// the try catch block below is left specifically for
// optimization and perf reasons. a tryCatcher is not necessary here.
FilterSubscriber.prototype._next = function (value) {
var result;
try {
result = this.predicate.call(this.thisArg, value, this.count++);
}
catch (err) {
this.destination.error(err);
return;
}
if (result) {
this.destination.next(value);
}
};
return FilterSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=filter.js.map
/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* An error thrown when an action is invalid because the object has been
* unsubscribed.
*
* @see {@link Subject}
* @see {@link BehaviorSubject}
*
* @class ObjectUnsubscribedError
*/
var ObjectUnsubscribedError = (function (_super) {
__extends(ObjectUnsubscribedError, _super);
function ObjectUnsubscribedError() {
var err = _super.call(this, 'object unsubscribed');
this.name = err.name = 'ObjectUnsubscribedError';
this.stack = err.stack;
this.message = err.message;
}
return ObjectUnsubscribedError;
}(Error));
exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
//# sourceMappingURL=ObjectUnsubscribedError.js.map
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
//# sourceMappingURL=isArrayLike.js.map
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function isDate(value) {
return value instanceof Date && !isNaN(+value);
}
exports.isDate = isDate;
//# sourceMappingURL=isDate.js.map
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isArray_1 = __webpack_require__(47);
function isNumeric(val) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
}
exports.isNumeric = isNumeric;
;
//# sourceMappingURL=isNumeric.js.map
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function isObject(x) {
return x != null && typeof x === 'object';
}
exports.isObject = isObject;
//# sourceMappingURL=isObject.js.map
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function isPromise(value) {
return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
}
exports.isPromise = isPromise;
//# sourceMappingURL=isPromise.js.map
/***/ }),
/* 118 */,
/* 119 */,
/* 120 */,
/* 121 */,
/* 122 */,
/* 123 */,
/* 124 */,
/* 125 */,
/* 126 */,
/* 127 */,
/* 128 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(1);
/* unused harmony export VERSION */
/* unused harmony export TEMPLATE_TRANSFORMS */
/* unused harmony export CompilerConfig */
/* unused harmony export JitCompiler */
/* unused harmony export DirectiveResolver */
/* unused harmony export PipeResolver */
/* unused harmony export NgModuleResolver */
/* unused harmony export DEFAULT_INTERPOLATION_CONFIG */
/* unused harmony export InterpolationConfig */
/* unused harmony export NgModuleCompiler */
/* unused harmony export ViewCompiler */
/* unused harmony export isSyntaxError */
/* unused harmony export syntaxError */
/* unused harmony export TextAst */
/* unused harmony export BoundTextAst */
/* unused harmony export AttrAst */
/* unused harmony export BoundElementPropertyAst */
/* unused harmony export BoundEventAst */
/* unused harmony export ReferenceAst */
/* unused harmony export VariableAst */
/* unused harmony export ElementAst */
/* unused harmony export EmbeddedTemplateAst */
/* unused harmony export BoundDirectivePropertyAst */
/* unused harmony export DirectiveAst */
/* unused harmony export ProviderAst */
/* unused harmony export ProviderAstType */
/* unused harmony export NgContentAst */
/* unused harmony export PropertyBindingType */
/* unused harmony export templateVisitAll */
/* unused harmony export CompileAnimationEntryMetadata */
/* unused harmony export CompileAnimationStateMetadata */
/* unused harmony export CompileAnimationStateDeclarationMetadata */
/* unused harmony export CompileAnimationStateTransitionMetadata */
/* unused harmony export CompileAnimationMetadata */
/* unused harmony export CompileAnimationKeyframesSequenceMetadata */
/* unused harmony export CompileAnimationStyleMetadata */
/* unused harmony export CompileAnimationAnimateMetadata */
/* unused harmony export CompileAnimationWithStepsMetadata */
/* unused harmony export CompileAnimationSequenceMetadata */
/* unused harmony export CompileAnimationGroupMetadata */
/* unused harmony export identifierName */
/* unused harmony export identifierModuleUrl */
/* unused harmony export viewClassName */
/* unused harmony export rendererTypeName */
/* unused harmony export hostViewClassName */
/* unused harmony export dirWrapperClassName */
/* unused harmony export componentFactoryName */
/* unused harmony export CompileSummaryKind */
/* unused harmony export tokenName */
/* unused harmony export tokenReference */
/* unused harmony export CompileStylesheetMetadata */
/* unused harmony export CompileTemplateMetadata */
/* unused harmony export CompileDirectiveMetadata */
/* unused harmony export createHostComponentMeta */
/* unused harmony export CompilePipeMetadata */
/* unused harmony export CompileNgModuleMetadata */
/* unused harmony export TransitiveCompileNgModuleMetadata */
/* unused harmony export ProviderMeta */
/* unused harmony export flatten */
/* unused harmony export sourceUrl */
/* unused harmony export templateSourceUrl */
/* unused harmony export sharedStylesheetJitUrl */
/* unused harmony export ngModuleJitUrl */
/* unused harmony export templateJitUrl */
/* unused harmony export createAotCompiler */
/* unused harmony export AotCompiler */
/* unused harmony export analyzeNgModules */
/* unused harmony export analyzeAndValidateNgModules */
/* unused harmony export extractProgramSymbols */
/* unused harmony export GeneratedFile */
/* unused harmony export StaticReflector */
/* unused harmony export StaticAndDynamicReflectionCapabilities */
/* unused harmony export StaticSymbol */
/* unused harmony export StaticSymbolCache */
/* unused harmony export ResolvedStaticSymbol */
/* unused harmony export StaticSymbolResolver */
/* unused harmony export unescapeIdentifier */
/* unused harmony export AotSummaryResolver */
/* unused harmony export SummaryResolver */
/* unused harmony export i18nHtmlParserFactory */
/* unused harmony export COMPILER_PROVIDERS */
/* unused harmony export JitCompilerFactory */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return platformCoreDynamic; });
/* unused harmony export createUrlResolverWithoutPackagePrefix */
/* unused harmony export createOfflineCompileUrlResolver */
/* unused harmony export DEFAULT_PACKAGE_URL_PROVIDER */
/* unused harmony export UrlResolver */
/* unused harmony export getUrlScheme */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ResourceLoader; });
/* unused harmony export ElementSchemaRegistry */
/* unused harmony export Extractor */
/* unused harmony export I18NHtmlParser */
/* unused harmony export MessageBundle */
/* unused harmony export Serializer */
/* unused harmony export Xliff */
/* unused harmony export Xliff2 */
/* unused harmony export Xmb */
/* unused harmony export Xtb */
/* unused harmony export DirectiveNormalizer */
/* unused harmony export ParserError */
/* unused harmony export ParseSpan */
/* unused harmony export AST */
/* unused harmony export Quote */
/* unused harmony export EmptyExpr */
/* unused harmony export ImplicitReceiver */
/* unused harmony export Chain */
/* unused harmony export Conditional */
/* unused harmony export PropertyRead */
/* unused harmony export PropertyWrite */
/* unused harmony export SafePropertyRead */
/* unused harmony export KeyedRead */
/* unused harmony export KeyedWrite */
/* unused harmony export BindingPipe */
/* unused harmony export LiteralPrimitive */
/* unused harmony export LiteralArray */
/* unused harmony export LiteralMap */
/* unused harmony export Interpolation */
/* unused harmony export Binary */
/* unused harmony export PrefixNot */
/* unused harmony export MethodCall */
/* unused harmony export SafeMethodCall */
/* unused harmony export FunctionCall */
/* unused harmony export ASTWithSource */
/* unused harmony export TemplateBinding */
/* unused harmony export RecursiveAstVisitor */
/* unused harmony export AstTransformer */
/* unused harmony export TokenType */
/* unused harmony export Lexer */
/* unused harmony export Token */
/* unused harmony export EOF */
/* unused harmony export isIdentifier */
/* unused harmony export isQuote */
/* unused harmony export SplitInterpolation */
/* unused harmony export TemplateBindingParseResult */
/* unused harmony export Parser */
/* unused harmony export _ParseAST */
/* unused harmony export ERROR_COLLECTOR_TOKEN */
/* unused harmony export CompileMetadataResolver */
/* unused harmony export componentModuleUrl */
/* unused harmony export Text */
/* unused harmony export Expansion */
/* unused harmony export ExpansionCase */
/* unused harmony export Attribute */
/* unused harmony export Element */
/* unused harmony export Comment */
/* unused harmony export visitAll */
/* unused harmony export ParseTreeResult */
/* unused harmony export TreeError */
/* unused harmony export HtmlParser */
/* unused harmony export HtmlTagDefinition */
/* unused harmony export getHtmlTagDefinition */
/* unused harmony export TagContentType */
/* unused harmony export splitNsName */
/* unused harmony export isNgContainer */
/* unused harmony export isNgContent */
/* unused harmony export isNgTemplate */
/* unused harmony export getNsPrefix */
/* unused harmony export mergeNsAndName */
/* unused harmony export NAMED_ENTITIES */
/* unused harmony export ImportResolver */
/* unused harmony export debugOutputAstAsTypeScript */
/* unused harmony export TypeScriptEmitter */
/* unused harmony export ParseLocation */
/* unused harmony export ParseSourceFile */
/* unused harmony export ParseSourceSpan */
/* unused harmony export ParseErrorLevel */
/* unused harmony export ParseError */
/* unused harmony export typeSourceSpan */
/* unused harmony export DomElementSchemaRegistry */
/* unused harmony export CssSelector */
/* unused harmony export SelectorMatcher */
/* unused harmony export SelectorListContext */
/* unused harmony export SelectorContext */
/* unused harmony export StylesCompileDependency */
/* unused harmony export StylesCompileResult */
/* unused harmony export CompiledStylesheet */
/* unused harmony export StyleCompiler */
/* unused harmony export TemplateParseError */
/* unused harmony export TemplateParseResult */
/* unused harmony export TemplateParser */
/* unused harmony export splitClasses */
/* unused harmony export createElementCssSelector */
/* unused harmony export removeSummaryDuplicates */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.1
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
var VERSION = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["u" /* Version */]('4.1.1');
/**
* @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
*/
/**
* A segment of text within the template.
*/
var TextAst = (function () {
/**
* @param {?} value
* @param {?} ngContentIndex
* @param {?} sourceSpan
*/
function TextAst(value, ngContentIndex, sourceSpan) {
this.value = value;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
TextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
return TextAst;
}());
/**
* A bound expression within the text of a template.
*/
var BoundTextAst = (function () {
/**
* @param {?} value
* @param {?} ngContentIndex
* @param {?} sourceSpan
*/
function BoundTextAst(value, ngContentIndex, sourceSpan) {
this.value = value;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
BoundTextAst.prototype.visit = function (visitor, context) {
return visitor.visitBoundText(this, context);
};
return BoundTextAst;
}());
/**
* A plain attribute on an element.
*/
var AttrAst = (function () {
/**
* @param {?} name
* @param {?} value
* @param {?} sourceSpan
*/
function AttrAst(name, value, sourceSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
AttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); };
return AttrAst;
}());
/**
* A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g.
* `[\@trigger]="stateExp"`)
*/
var BoundElementPropertyAst = (function () {
/**
* @param {?} name
* @param {?} type
* @param {?} securityContext
* @param {?} value
* @param {?} unit
* @param {?} sourceSpan
*/
function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) {
this.name = name;
this.type = type;
this.securityContext = securityContext;
this.value = value;
this.unit = unit;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
BoundElementPropertyAst.prototype.visit = function (visitor, context) {
return visitor.visitElementProperty(this, context);
};
Object.defineProperty(BoundElementPropertyAst.prototype, "isAnimation", {
/**
* @return {?}
*/
get: function () { return this.type === PropertyBindingType.Animation; },
enumerable: true,
configurable: true
});
return BoundElementPropertyAst;
}());
/**
* A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g.
* `(\@trigger.phase)="callback($event)"`).
*/
var BoundEventAst = (function () {
/**
* @param {?} name
* @param {?} target
* @param {?} phase
* @param {?} handler
* @param {?} sourceSpan
*/
function BoundEventAst(name, target, phase, handler, sourceSpan) {
this.name = name;
this.target = target;
this.phase = phase;
this.handler = handler;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} name
* @param {?} target
* @param {?} phase
* @return {?}
*/
BoundEventAst.calcFullName = function (name, target, phase) {
if (target) {
return target + ":" + name;
}
else if (phase) {
return "@" + name + "." + phase;
}
else {
return name;
}
};
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
BoundEventAst.prototype.visit = function (visitor, context) {
return visitor.visitEvent(this, context);
};
Object.defineProperty(BoundEventAst.prototype, "fullName", {
/**
* @return {?}
*/
get: function () { return BoundEventAst.calcFullName(this.name, this.target, this.phase); },
enumerable: true,
configurable: true
});
Object.defineProperty(BoundEventAst.prototype, "isAnimation", {
/**
* @return {?}
*/
get: function () { return !!this.phase; },
enumerable: true,
configurable: true
});
return BoundEventAst;
}());
/**
* A reference declaration on an element (e.g. `let someName="expression"`).
*/
var ReferenceAst = (function () {
/**
* @param {?} name
* @param {?} value
* @param {?} sourceSpan
*/
function ReferenceAst(name, value, sourceSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ReferenceAst.prototype.visit = function (visitor, context) {
return visitor.visitReference(this, context);
};
return ReferenceAst;
}());
/**
* A variable declaration on a <ng-template> (e.g. `var-someName="someLocalName"`).
*/
var VariableAst = (function () {
/**
* @param {?} name
* @param {?} value
* @param {?} sourceSpan
*/
function VariableAst(name, value, sourceSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
VariableAst.prototype.visit = function (visitor, context) {
return visitor.visitVariable(this, context);
};
return VariableAst;
}());
/**
* An element declaration in a template.
*/
var ElementAst = (function () {
/**
* @param {?} name
* @param {?} attrs
* @param {?} inputs
* @param {?} outputs
* @param {?} references
* @param {?} directives
* @param {?} providers
* @param {?} hasViewContainer
* @param {?} queryMatches
* @param {?} children
* @param {?} ngContentIndex
* @param {?} sourceSpan
* @param {?} endSourceSpan
*/
function ElementAst(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) {
this.name = name;
this.attrs = attrs;
this.inputs = inputs;
this.outputs = outputs;
this.references = references;
this.directives = directives;
this.providers = providers;
this.hasViewContainer = hasViewContainer;
this.queryMatches = queryMatches;
this.children = children;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
this.endSourceSpan = endSourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ElementAst.prototype.visit = function (visitor, context) {
return visitor.visitElement(this, context);
};
return ElementAst;
}());
/**
* A `<ng-template>` element included in an Angular template.
*/
var EmbeddedTemplateAst = (function () {
/**
* @param {?} attrs
* @param {?} outputs
* @param {?} references
* @param {?} variables
* @param {?} directives
* @param {?} providers
* @param {?} hasViewContainer
* @param {?} queryMatches
* @param {?} children
* @param {?} ngContentIndex
* @param {?} sourceSpan
*/
function EmbeddedTemplateAst(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) {
this.attrs = attrs;
this.outputs = outputs;
this.references = references;
this.variables = variables;
this.directives = directives;
this.providers = providers;
this.hasViewContainer = hasViewContainer;
this.queryMatches = queryMatches;
this.children = children;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
EmbeddedTemplateAst.prototype.visit = function (visitor, context) {
return visitor.visitEmbeddedTemplate(this, context);
};
return EmbeddedTemplateAst;
}());
/**
* A directive property with a bound value (e.g. `*ngIf="condition").
*/
var BoundDirectivePropertyAst = (function () {
/**
* @param {?} directiveName
* @param {?} templateName
* @param {?} value
* @param {?} sourceSpan
*/
function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) {
this.directiveName = directiveName;
this.templateName = templateName;
this.value = value;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
BoundDirectivePropertyAst.prototype.visit = function (visitor, context) {
return visitor.visitDirectiveProperty(this, context);
};
return BoundDirectivePropertyAst;
}());
/**
* A directive declared on an element.
*/
var DirectiveAst = (function () {
/**
* @param {?} directive
* @param {?} inputs
* @param {?} hostProperties
* @param {?} hostEvents
* @param {?} contentQueryStartId
* @param {?} sourceSpan
*/
function DirectiveAst(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) {
this.directive = directive;
this.inputs = inputs;
this.hostProperties = hostProperties;
this.hostEvents = hostEvents;
this.contentQueryStartId = contentQueryStartId;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
DirectiveAst.prototype.visit = function (visitor, context) {
return visitor.visitDirective(this, context);
};
return DirectiveAst;
}());
/**
* A provider declared on an element
*/
var ProviderAst = (function () {
/**
* @param {?} token
* @param {?} multiProvider
* @param {?} eager
* @param {?} providers
* @param {?} providerType
* @param {?} lifecycleHooks
* @param {?} sourceSpan
*/
function ProviderAst(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan) {
this.token = token;
this.multiProvider = multiProvider;
this.eager = eager;
this.providers = providers;
this.providerType = providerType;
this.lifecycleHooks = lifecycleHooks;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ProviderAst.prototype.visit = function (visitor, context) {
// No visit method in the visitor for now...
return null;
};
return ProviderAst;
}());
var ProviderAstType = {};
ProviderAstType.PublicService = 0;
ProviderAstType.PrivateService = 1;
ProviderAstType.Component = 2;
ProviderAstType.Directive = 3;
ProviderAstType.Builtin = 4;
ProviderAstType[ProviderAstType.PublicService] = "PublicService";
ProviderAstType[ProviderAstType.PrivateService] = "PrivateService";
ProviderAstType[ProviderAstType.Component] = "Component";
ProviderAstType[ProviderAstType.Directive] = "Directive";
ProviderAstType[ProviderAstType.Builtin] = "Builtin";
/**
* Position where content is to be projected (instance of `<ng-content>` in a template).
*/
var NgContentAst = (function () {
/**
* @param {?} index
* @param {?} ngContentIndex
* @param {?} sourceSpan
*/
function NgContentAst(index, ngContentIndex, sourceSpan) {
this.index = index;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
NgContentAst.prototype.visit = function (visitor, context) {
return visitor.visitNgContent(this, context);
};
return NgContentAst;
}());
var PropertyBindingType = {};
PropertyBindingType.Property = 0;
PropertyBindingType.Attribute = 1;
PropertyBindingType.Class = 2;
PropertyBindingType.Style = 3;
PropertyBindingType.Animation = 4;
PropertyBindingType[PropertyBindingType.Property] = "Property";
PropertyBindingType[PropertyBindingType.Attribute] = "Attribute";
PropertyBindingType[PropertyBindingType.Class] = "Class";
PropertyBindingType[PropertyBindingType.Style] = "Style";
PropertyBindingType[PropertyBindingType.Animation] = "Animation";
/**
* Visit every node in a list of {\@link TemplateAst}s with the given {\@link TemplateAstVisitor}.
* @param {?} visitor
* @param {?} asts
* @param {?=} context
* @return {?}
*/
function templateVisitAll(visitor, asts, context) {
if (context === void 0) { context = null; }
var /** @type {?} */ result = [];
var /** @type {?} */ visit = visitor.visit ?
function (ast) { return ((visitor.visit))(ast, context) || ast.visit(visitor, context); } :
function (ast) { return ast.visit(visitor, context); };
asts.forEach(function (ast) {
var /** @type {?} */ astResult = visit(ast);
if (astResult) {
result.push(astResult);
}
});
return result;
}
/**
* A token representing the a reference to a static type.
*
* This token is unique for a filePath and name and can be used as a hash table key.
*/
var StaticSymbol = (function () {
/**
* @param {?} filePath
* @param {?} name
* @param {?} members
*/
function StaticSymbol(filePath, name, members) {
this.filePath = filePath;
this.name = name;
this.members = members;
}
/**
* @return {?}
*/
StaticSymbol.prototype.assertNoMembers = function () {
if (this.members.length) {
throw new Error("Illegal state: symbol without members expected, but got " + JSON.stringify(this) + ".");
}
};
return StaticSymbol;
}());
/**
* A cache of static symbol used by the StaticReflector to return the same symbol for the
* same symbol values.
*/
var StaticSymbolCache = (function () {
function StaticSymbolCache() {
this.cache = new Map();
}
/**
* @param {?} declarationFile
* @param {?} name
* @param {?=} members
* @return {?}
*/
StaticSymbolCache.prototype.get = function (declarationFile, name, members) {
members = members || [];
var /** @type {?} */ memberSuffix = members.length ? "." + members.join('.') : '';
var /** @type {?} */ key = "\"" + declarationFile + "\"." + name + memberSuffix;
var /** @type {?} */ result = this.cache.get(key);
if (!result) {
result = new StaticSymbol(declarationFile, name, members);
this.cache.set(key, result);
}
return result;
};
return StaticSymbolCache;
}());
var TagContentType = {};
TagContentType.RAW_TEXT = 0;
TagContentType.ESCAPABLE_RAW_TEXT = 1;
TagContentType.PARSABLE_DATA = 2;
TagContentType[TagContentType.RAW_TEXT] = "RAW_TEXT";
TagContentType[TagContentType.ESCAPABLE_RAW_TEXT] = "ESCAPABLE_RAW_TEXT";
TagContentType[TagContentType.PARSABLE_DATA] = "PARSABLE_DATA";
/**
* @param {?} elementName
* @return {?}
*/
function splitNsName(elementName) {
if (elementName[0] != ':') {
return [null, elementName];
}
var /** @type {?} */ colonIndex = elementName.indexOf(':', 1);
if (colonIndex == -1) {
throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\"");
}
return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
}
/**
* @param {?} tagName
* @return {?}
*/
function isNgContainer(tagName) {
return splitNsName(tagName)[1] === 'ng-container';
}
/**
* @param {?} tagName
* @return {?}
*/
function isNgContent(tagName) {
return splitNsName(tagName)[1] === 'ng-content';
}
/**
* @param {?} tagName
* @return {?}
*/
function isNgTemplate(tagName) {
return splitNsName(tagName)[1] === 'ng-template';
}
/**
* @param {?} fullName
* @return {?}
*/
function getNsPrefix(fullName) {
return fullName === null ? null : splitNsName(fullName)[0];
}
/**
* @param {?} prefix
* @param {?} localName
* @return {?}
*/
function mergeNsAndName(prefix, localName) {
return prefix ? ":" + prefix + ":" + localName : localName;
}
// see http://www.w3.org/TR/html51/syntax.html#named-character-references
// see https://html.spec.whatwg.org/multipage/entities.json
// This list is not exhaustive to keep the compiler footprint low.
// The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not
// exist.
var NAMED_ENTITIES = {
'Aacute': '\u00C1',
'aacute': '\u00E1',
'Acirc': '\u00C2',
'acirc': '\u00E2',
'acute': '\u00B4',
'AElig': '\u00C6',
'aelig': '\u00E6',
'Agrave': '\u00C0',
'agrave': '\u00E0',
'alefsym': '\u2135',
'Alpha': '\u0391',
'alpha': '\u03B1',
'amp': '&',
'and': '\u2227',
'ang': '\u2220',
'apos': '\u0027',
'Aring': '\u00C5',
'aring': '\u00E5',
'asymp': '\u2248',
'Atilde': '\u00C3',
'atilde': '\u00E3',
'Auml': '\u00C4',
'auml': '\u00E4',
'bdquo': '\u201E',
'Beta': '\u0392',
'beta': '\u03B2',
'brvbar': '\u00A6',
'bull': '\u2022',
'cap': '\u2229',
'Ccedil': '\u00C7',
'ccedil': '\u00E7',
'cedil': '\u00B8',
'cent': '\u00A2',
'Chi': '\u03A7',
'chi': '\u03C7',
'circ': '\u02C6',
'clubs': '\u2663',
'cong': '\u2245',
'copy': '\u00A9',
'crarr': '\u21B5',
'cup': '\u222A',
'curren': '\u00A4',
'dagger': '\u2020',
'Dagger': '\u2021',
'darr': '\u2193',
'dArr': '\u21D3',
'deg': '\u00B0',
'Delta': '\u0394',
'delta': '\u03B4',
'diams': '\u2666',
'divide': '\u00F7',
'Eacute': '\u00C9',
'eacute': '\u00E9',
'Ecirc': '\u00CA',
'ecirc': '\u00EA',
'Egrave': '\u00C8',
'egrave': '\u00E8',
'empty': '\u2205',
'emsp': '\u2003',
'ensp': '\u2002',
'Epsilon': '\u0395',
'epsilon': '\u03B5',
'equiv': '\u2261',
'Eta': '\u0397',
'eta': '\u03B7',
'ETH': '\u00D0',
'eth': '\u00F0',
'Euml': '\u00CB',
'euml': '\u00EB',
'euro': '\u20AC',
'exist': '\u2203',
'fnof': '\u0192',
'forall': '\u2200',
'frac12': '\u00BD',
'frac14': '\u00BC',
'frac34': '\u00BE',
'frasl': '\u2044',
'Gamma': '\u0393',
'gamma': '\u03B3',
'ge': '\u2265',
'gt': '>',
'harr': '\u2194',
'hArr': '\u21D4',
'hearts': '\u2665',
'hellip': '\u2026',
'Iacute': '\u00CD',
'iacute': '\u00ED',
'Icirc': '\u00CE',
'icirc': '\u00EE',
'iexcl': '\u00A1',
'Igrave': '\u00CC',
'igrave': '\u00EC',
'image': '\u2111',
'infin': '\u221E',
'int': '\u222B',
'Iota': '\u0399',
'iota': '\u03B9',
'iquest': '\u00BF',
'isin': '\u2208',
'Iuml': '\u00CF',
'iuml': '\u00EF',
'Kappa': '\u039A',
'kappa': '\u03BA',
'Lambda': '\u039B',
'lambda': '\u03BB',
'lang': '\u27E8',
'laquo': '\u00AB',
'larr': '\u2190',
'lArr': '\u21D0',
'lceil': '\u2308',
'ldquo': '\u201C',
'le': '\u2264',
'lfloor': '\u230A',
'lowast': '\u2217',
'loz': '\u25CA',
'lrm': '\u200E',
'lsaquo': '\u2039',
'lsquo': '\u2018',
'lt': '<',
'macr': '\u00AF',
'mdash': '\u2014',
'micro': '\u00B5',
'middot': '\u00B7',
'minus': '\u2212',
'Mu': '\u039C',
'mu': '\u03BC',
'nabla': '\u2207',
'nbsp': '\u00A0',
'ndash': '\u2013',
'ne': '\u2260',
'ni': '\u220B',
'not': '\u00AC',
'notin': '\u2209',
'nsub': '\u2284',
'Ntilde': '\u00D1',
'ntilde': '\u00F1',
'Nu': '\u039D',
'nu': '\u03BD',
'Oacute': '\u00D3',
'oacute': '\u00F3',
'Ocirc': '\u00D4',
'ocirc': '\u00F4',
'OElig': '\u0152',
'oelig': '\u0153',
'Ograve': '\u00D2',
'ograve': '\u00F2',
'oline': '\u203E',
'Omega': '\u03A9',
'omega': '\u03C9',
'Omicron': '\u039F',
'omicron': '\u03BF',
'oplus': '\u2295',
'or': '\u2228',
'ordf': '\u00AA',
'ordm': '\u00BA',
'Oslash': '\u00D8',
'oslash': '\u00F8',
'Otilde': '\u00D5',
'otilde': '\u00F5',
'otimes': '\u2297',
'Ouml': '\u00D6',
'ouml': '\u00F6',
'para': '\u00B6',
'permil': '\u2030',
'perp': '\u22A5',
'Phi': '\u03A6',
'phi': '\u03C6',
'Pi': '\u03A0',
'pi': '\u03C0',
'piv': '\u03D6',
'plusmn': '\u00B1',
'pound': '\u00A3',
'prime': '\u2032',
'Prime': '\u2033',
'prod': '\u220F',
'prop': '\u221D',
'Psi': '\u03A8',
'psi': '\u03C8',
'quot': '\u0022',
'radic': '\u221A',
'rang': '\u27E9',
'raquo': '\u00BB',
'rarr': '\u2192',
'rArr': '\u21D2',
'rceil': '\u2309',
'rdquo': '\u201D',
'real': '\u211C',
'reg': '\u00AE',
'rfloor': '\u230B',
'Rho': '\u03A1',
'rho': '\u03C1',
'rlm': '\u200F',
'rsaquo': '\u203A',
'rsquo': '\u2019',
'sbquo': '\u201A',
'Scaron': '\u0160',
'scaron': '\u0161',
'sdot': '\u22C5',
'sect': '\u00A7',
'shy': '\u00AD',
'Sigma': '\u03A3',
'sigma': '\u03C3',
'sigmaf': '\u03C2',
'sim': '\u223C',
'spades': '\u2660',
'sub': '\u2282',
'sube': '\u2286',
'sum': '\u2211',
'sup': '\u2283',
'sup1': '\u00B9',
'sup2': '\u00B2',
'sup3': '\u00B3',
'supe': '\u2287',
'szlig': '\u00DF',
'Tau': '\u03A4',
'tau': '\u03C4',
'there4': '\u2234',
'Theta': '\u0398',
'theta': '\u03B8',
'thetasym': '\u03D1',
'thinsp': '\u2009',
'THORN': '\u00DE',
'thorn': '\u00FE',
'tilde': '\u02DC',
'times': '\u00D7',
'trade': '\u2122',
'Uacute': '\u00DA',
'uacute': '\u00FA',
'uarr': '\u2191',
'uArr': '\u21D1',
'Ucirc': '\u00DB',
'ucirc': '\u00FB',
'Ugrave': '\u00D9',
'ugrave': '\u00F9',
'uml': '\u00A8',
'upsih': '\u03D2',
'Upsilon': '\u03A5',
'upsilon': '\u03C5',
'Uuml': '\u00DC',
'uuml': '\u00FC',
'weierp': '\u2118',
'Xi': '\u039E',
'xi': '\u03BE',
'Yacute': '\u00DD',
'yacute': '\u00FD',
'yen': '\u00A5',
'yuml': '\u00FF',
'Yuml': '\u0178',
'Zeta': '\u0396',
'zeta': '\u03B6',
'zwj': '\u200D',
'zwnj': '\u200C',
};
/**
* @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
*/
var HtmlTagDefinition = (function () {
/**
* @param {?=} __0
*/
function HtmlTagDefinition(_a) {
var _b = _a === void 0 ? {} : _a, closedByChildren = _b.closedByChildren, requiredParents = _b.requiredParents, implicitNamespacePrefix = _b.implicitNamespacePrefix, _c = _b.contentType, contentType = _c === void 0 ? TagContentType.PARSABLE_DATA : _c, _d = _b.closedByParent, closedByParent = _d === void 0 ? false : _d, _e = _b.isVoid, isVoid = _e === void 0 ? false : _e, _f = _b.ignoreFirstLf, ignoreFirstLf = _f === void 0 ? false : _f;
var _this = this;
this.closedByChildren = {};
this.closedByParent = false;
this.canSelfClose = false;
if (closedByChildren && closedByChildren.length > 0) {
closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; });
}
this.isVoid = isVoid;
this.closedByParent = closedByParent || isVoid;
if (requiredParents && requiredParents.length > 0) {
this.requiredParents = {};
// The first parent is the list is automatically when none of the listed parents are present
this.parentToAdd = requiredParents[0];
requiredParents.forEach(function (tagName) { return _this.requiredParents[tagName] = true; });
}
this.implicitNamespacePrefix = implicitNamespacePrefix || null;
this.contentType = contentType;
this.ignoreFirstLf = ignoreFirstLf;
}
/**
* @param {?} currentParent
* @return {?}
*/
HtmlTagDefinition.prototype.requireExtraParent = function (currentParent) {
if (!this.requiredParents) {
return false;
}
if (!currentParent) {
return true;
}
var /** @type {?} */ lcParent = currentParent.toLowerCase();
var /** @type {?} */ isParentTemplate = lcParent === 'template' || currentParent === 'ng-template';
return !isParentTemplate && this.requiredParents[lcParent] != true;
};
/**
* @param {?} name
* @return {?}
*/
HtmlTagDefinition.prototype.isClosedByChild = function (name) {
return this.isVoid || name.toLowerCase() in this.closedByChildren;
};
return HtmlTagDefinition;
}());
// see http://www.w3.org/TR/html51/syntax.html#optional-tags
// This implementation does not fully conform to the HTML5 spec.
var TAG_DEFINITIONS = {
'base': new HtmlTagDefinition({ isVoid: true }),
'meta': new HtmlTagDefinition({ isVoid: true }),
'area': new HtmlTagDefinition({ isVoid: true }),
'embed': new HtmlTagDefinition({ isVoid: true }),
'link': new HtmlTagDefinition({ isVoid: true }),
'img': new HtmlTagDefinition({ isVoid: true }),
'input': new HtmlTagDefinition({ isVoid: true }),
'param': new HtmlTagDefinition({ isVoid: true }),
'hr': new HtmlTagDefinition({ isVoid: true }),
'br': new HtmlTagDefinition({ isVoid: true }),
'source': new HtmlTagDefinition({ isVoid: true }),
'track': new HtmlTagDefinition({ isVoid: true }),
'wbr': new HtmlTagDefinition({ isVoid: true }),
'p': new HtmlTagDefinition({
closedByChildren: [
'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr',
'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'
],
closedByParent: true
}),
'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
'tr': new HtmlTagDefinition({
closedByChildren: ['tr'],
requiredParents: ['tbody', 'tfoot', 'thead'],
closedByParent: true
}),
'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
'col': new HtmlTagDefinition({ requiredParents: ['colgroup'], isVoid: true }),
'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
'title': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT }),
'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
};
var _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
/**
* @param {?} tagName
* @return {?}
*/
function getHtmlTagDefinition(tagName) {
return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION;
}
/**
* @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
*/
var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' +
'([-\\w]+)|' +
'(?:\\.([-\\w]+))|' +
// "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
'(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' +
// "[name="value"]",
// "[name='value']"
'(\\))|' +
'(\\s*,\\s*)', // ","
'g');
/**
* A css selector contains an element name,
* css classes and attribute/value pairs with the purpose
* of selecting subsets out of them.
*/
var CssSelector = (function () {
function CssSelector() {
this.element = null;
this.classNames = [];
this.attrs = [];
this.notSelectors = [];
}
/**
* @param {?} selector
* @return {?}
*/
CssSelector.parse = function (selector) {
var /** @type {?} */ results = [];
var /** @type {?} */ _addResult = function (res, cssSel) {
if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
cssSel.attrs.length == 0) {
cssSel.element = '*';
}
res.push(cssSel);
};
var /** @type {?} */ cssSelector = new CssSelector();
var /** @type {?} */ match;
var /** @type {?} */ current = cssSelector;
var /** @type {?} */ inNot = false;
_SELECTOR_REGEXP.lastIndex = 0;
while (match = _SELECTOR_REGEXP.exec(selector)) {
if (match[1]) {
if (inNot) {
throw new Error('Nesting :not is not allowed in a selector');
}
inNot = true;
current = new CssSelector();
cssSelector.notSelectors.push(current);
}
if (match[2]) {
current.setElement(match[2]);
}
if (match[3]) {
current.addClassName(match[3]);
}
if (match[4]) {
current.addAttribute(match[4], match[6]);
}
if (match[7]) {
inNot = false;
current = cssSelector;
}
if (match[8]) {
if (inNot) {
throw new Error('Multiple selectors in :not are not supported');
}
_addResult(results, cssSelector);
cssSelector = current = new CssSelector();
}
}
_addResult(results, cssSelector);
return results;
};
/**
* @return {?}
*/
CssSelector.prototype.isElementSelector = function () {
return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
this.notSelectors.length === 0;
};
/**
* @return {?}
*/
CssSelector.prototype.hasElementSelector = function () { return !!this.element; };
/**
* @param {?=} element
* @return {?}
*/
CssSelector.prototype.setElement = function (element) {
if (element === void 0) { element = null; }
this.element = element;
};
/**
* Gets a template string for an element that matches the selector.
* @return {?}
*/
CssSelector.prototype.getMatchingElementTemplate = function () {
var /** @type {?} */ tagName = this.element || 'div';
var /** @type {?} */ classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : '';
var /** @type {?} */ attrs = '';
for (var /** @type {?} */ i = 0; i < this.attrs.length; i += 2) {
var /** @type {?} */ attrName = this.attrs[i];
var /** @type {?} */ attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : '';
attrs += " " + attrName + attrValue;
}
return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" :
"<" + tagName + classAttr + attrs + "></" + tagName + ">";
};
/**
* @param {?} name
* @param {?=} value
* @return {?}
*/
CssSelector.prototype.addAttribute = function (name, value) {
if (value === void 0) { value = ''; }
this.attrs.push(name, value && value.toLowerCase() || '');
};
/**
* @param {?} name
* @return {?}
*/
CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); };
/**
* @return {?}
*/
CssSelector.prototype.toString = function () {
var /** @type {?} */ res = this.element || '';
if (this.classNames) {
this.classNames.forEach(function (klass) { return res += "." + klass; });
}
if (this.attrs) {
for (var /** @type {?} */ i = 0; i < this.attrs.length; i += 2) {
var /** @type {?} */ name = this.attrs[i];
var /** @type {?} */ value = this.attrs[i + 1];
res += "[" + name + (value ? '=' + value : '') + "]";
}
}
this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; });
return res;
};
return CssSelector;
}());
/**
* Reads a list of CssSelectors and allows to calculate which ones
* are contained in a given CssSelector.
*/
var SelectorMatcher = (function () {
function SelectorMatcher() {
this._elementMap = new Map();
this._elementPartialMap = new Map();
this._classMap = new Map();
this._classPartialMap = new Map();
this._attrValueMap = new Map();
this._attrValuePartialMap = new Map();
this._listContexts = [];
}
/**
* @param {?} notSelectors
* @return {?}
*/
SelectorMatcher.createNotMatcher = function (notSelectors) {
var /** @type {?} */ notMatcher = new SelectorMatcher();
notMatcher.addSelectables(notSelectors, null);
return notMatcher;
};
/**
* @param {?} cssSelectors
* @param {?=} callbackCtxt
* @return {?}
*/
SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) {
var /** @type {?} */ listContext = ((null));
if (cssSelectors.length > 1) {
listContext = new SelectorListContext(cssSelectors);
this._listContexts.push(listContext);
}
for (var /** @type {?} */ i = 0; i < cssSelectors.length; i++) {
this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
}
};
/**
* Add an object that can be found later on by calling `match`.
* @param {?} cssSelector A css selector
* @param {?} callbackCtxt An opaque object that will be given to the callback of the `match` function
* @param {?} listContext
* @return {?}
*/
SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) {
var /** @type {?} */ matcher = this;
var /** @type {?} */ element = cssSelector.element;
var /** @type {?} */ classNames = cssSelector.classNames;
var /** @type {?} */ attrs = cssSelector.attrs;
var /** @type {?} */ selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
if (element) {
var /** @type {?} */ isTerminal = attrs.length === 0 && classNames.length === 0;
if (isTerminal) {
this._addTerminal(matcher._elementMap, element, selectable);
}
else {
matcher = this._addPartial(matcher._elementPartialMap, element);
}
}
if (classNames) {
for (var /** @type {?} */ i = 0; i < classNames.length; i++) {
var /** @type {?} */ isTerminal = attrs.length === 0 && i === classNames.length - 1;
var /** @type {?} */ className = classNames[i];
if (isTerminal) {
this._addTerminal(matcher._classMap, className, selectable);
}
else {
matcher = this._addPartial(matcher._classPartialMap, className);
}
}
}
if (attrs) {
for (var /** @type {?} */ i = 0; i < attrs.length; i += 2) {
var /** @type {?} */ isTerminal = i === attrs.length - 2;
var /** @type {?} */ name = attrs[i];
var /** @type {?} */ value = attrs[i + 1];
if (isTerminal) {
var /** @type {?} */ terminalMap = matcher._attrValueMap;
var /** @type {?} */ terminalValuesMap = terminalMap.get(name);
if (!terminalValuesMap) {
terminalValuesMap = new Map();
terminalMap.set(name, terminalValuesMap);
}
this._addTerminal(terminalValuesMap, value, selectable);
}
else {
var /** @type {?} */ partialMap = matcher._attrValuePartialMap;
var /** @type {?} */ partialValuesMap = partialMap.get(name);
if (!partialValuesMap) {
partialValuesMap = new Map();
partialMap.set(name, partialValuesMap);
}
matcher = this._addPartial(partialValuesMap, value);
}
}
}
};
/**
* @param {?} map
* @param {?} name
* @param {?} selectable
* @return {?}
*/
SelectorMatcher.prototype._addTerminal = function (map, name, selectable) {
var /** @type {?} */ terminalList = map.get(name);
if (!terminalList) {
terminalList = [];
map.set(name, terminalList);
}
terminalList.push(selectable);
};
/**
* @param {?} map
* @param {?} name
* @return {?}
*/
SelectorMatcher.prototype._addPartial = function (map, name) {
var /** @type {?} */ matcher = map.get(name);
if (!matcher) {
matcher = new SelectorMatcher();
map.set(name, matcher);
}
return matcher;
};
/**
* Find the objects that have been added via `addSelectable`
* whose css selector is contained in the given css selector.
* @param {?} cssSelector A css selector
* @param {?} matchedCallback This callback will be called with the object handed into `addSelectable`
* @return {?} boolean true if a match was found
*/
SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) {
var /** @type {?} */ result = false;
var /** @type {?} */ element = ((cssSelector.element));
var /** @type {?} */ classNames = cssSelector.classNames;
var /** @type {?} */ attrs = cssSelector.attrs;
for (var /** @type {?} */ i = 0; i < this._listContexts.length; i++) {
this._listContexts[i].alreadyMatched = false;
}
result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
result;
if (classNames) {
for (var /** @type {?} */ i = 0; i < classNames.length; i++) {
var /** @type {?} */ className = classNames[i];
result =
this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
result =
this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
result;
}
}
if (attrs) {
for (var /** @type {?} */ i = 0; i < attrs.length; i += 2) {
var /** @type {?} */ name = attrs[i];
var /** @type {?} */ value = attrs[i + 1];
var /** @type {?} */ terminalValuesMap = ((this._attrValueMap.get(name)));
if (value) {
result =
this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
}
result =
this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
var /** @type {?} */ partialValuesMap = ((this._attrValuePartialMap.get(name)));
if (value) {
result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
}
result =
this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
}
}
return result;
};
/**
* \@internal
* @param {?} map
* @param {?} name
* @param {?} cssSelector
* @param {?} matchedCallback
* @return {?}
*/
SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) {
if (!map || typeof name !== 'string') {
return false;
}
var /** @type {?} */ selectables = map.get(name) || [];
var /** @type {?} */ starSelectables = ((map.get('*')));
if (starSelectables) {
selectables = selectables.concat(starSelectables);
}
if (selectables.length === 0) {
return false;
}
var /** @type {?} */ selectable;
var /** @type {?} */ result = false;
for (var /** @type {?} */ i = 0; i < selectables.length; i++) {
selectable = selectables[i];
result = selectable.finalize(cssSelector, matchedCallback) || result;
}
return result;
};
/**
* \@internal
* @param {?} map
* @param {?} name
* @param {?} cssSelector
* @param {?} matchedCallback
* @return {?}
*/
SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) {
if (!map || typeof name !== 'string') {
return false;
}
var /** @type {?} */ nestedSelector = map.get(name);
if (!nestedSelector) {
return false;
}
// TODO(perf): get rid of recursion and measure again
// TODO(perf): don't pass the whole selector into the recursion,
// but only the not processed parts
return nestedSelector.match(cssSelector, matchedCallback);
};
return SelectorMatcher;
}());
var SelectorListContext = (function () {
/**
* @param {?} selectors
*/
function SelectorListContext(selectors) {
this.selectors = selectors;
this.alreadyMatched = false;
}
return SelectorListContext;
}());
var SelectorContext = (function () {
/**
* @param {?} selector
* @param {?} cbContext
* @param {?} listContext
*/
function SelectorContext(selector, cbContext, listContext) {
this.selector = selector;
this.cbContext = cbContext;
this.listContext = listContext;
this.notSelectors = selector.notSelectors;
}
/**
* @param {?} cssSelector
* @param {?} callback
* @return {?}
*/
SelectorContext.prototype.finalize = function (cssSelector, callback) {
var /** @type {?} */ result = true;
if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
var /** @type {?} */ notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
result = !notMatcher.match(cssSelector, null);
}
if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
if (this.listContext) {
this.listContext.alreadyMatched = true;
}
callback(this.selector, this.cbContext);
}
return result;
};
return SelectorContext;
}());
/**
* @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
*/
var MODULE_SUFFIX = '';
var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
/**
* @param {?} input
* @return {?}
*/
/**
* @param {?} input
* @return {?}
*/
function dashCaseToCamelCase(input) {
return input.replace(DASH_CASE_REGEXP, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
return m[1].toUpperCase();
});
}
/**
* @param {?} input
* @param {?} defaultValues
* @return {?}
*/
function splitAtColon(input, defaultValues) {
return _splitAt(input, ':', defaultValues);
}
/**
* @param {?} input
* @param {?} defaultValues
* @return {?}
*/
function splitAtPeriod(input, defaultValues) {
return _splitAt(input, '.', defaultValues);
}
/**
* @param {?} input
* @param {?} character
* @param {?} defaultValues
* @return {?}
*/
function _splitAt(input, character, defaultValues) {
var /** @type {?} */ characterIndex = input.indexOf(character);
if (characterIndex == -1)
return defaultValues;
return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
}
/**
* @param {?} value
* @param {?} visitor
* @param {?} context
* @return {?}
*/
function visitValue(value, visitor, context) {
if (Array.isArray(value)) {
return visitor.visitArray(/** @type {?} */ (value), context);
}
if (isStrictStringMap(value)) {
return visitor.visitStringMap(/** @type {?} */ (value), context);
}
if (value == null || typeof value == 'string' || typeof value == 'number' ||
typeof value == 'boolean') {
return visitor.visitPrimitive(value, context);
}
return visitor.visitOther(value, context);
}
/**
* @param {?} val
* @return {?}
*/
function isDefined(val) {
return val !== null && val !== undefined;
}
/**
* @template T
* @param {?} val
* @return {?}
*/
function noUndefined(val) {
return val === undefined ? ((null)) : val;
}
var ValueTransformer = (function () {
function ValueTransformer() {
}
/**
* @param {?} arr
* @param {?} context
* @return {?}
*/
ValueTransformer.prototype.visitArray = function (arr, context) {
var _this = this;
return arr.map(function (value) { return visitValue(value, _this, context); });
};
/**
* @param {?} map
* @param {?} context
* @return {?}
*/
ValueTransformer.prototype.visitStringMap = function (map, context) {
var _this = this;
var /** @type {?} */ result = {};
Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); });
return result;
};
/**
* @param {?} value
* @param {?} context
* @return {?}
*/
ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; };
/**
* @param {?} value
* @param {?} context
* @return {?}
*/
ValueTransformer.prototype.visitOther = function (value, context) { return value; };
return ValueTransformer;
}());
var SyncAsyncResult = (function () {
/**
* @param {?} syncResult
* @param {?=} asyncResult
*/
function SyncAsyncResult(syncResult, asyncResult) {
if (asyncResult === void 0) { asyncResult = null; }
this.syncResult = syncResult;
this.asyncResult = asyncResult;
if (!asyncResult) {
this.asyncResult = Promise.resolve(syncResult);
}
}
return SyncAsyncResult;
}());
/**
* @param {?} msg
* @return {?}
*/
function syntaxError(msg) {
var /** @type {?} */ error = Error(msg);
((error))[ERROR_SYNTAX_ERROR] = true;
return error;
}
var ERROR_SYNTAX_ERROR = 'ngSyntaxError';
/**
* @param {?} error
* @return {?}
*/
function isSyntaxError(error) {
return ((error))[ERROR_SYNTAX_ERROR];
}
/**
* @param {?} s
* @return {?}
*/
function escapeRegExp(s) {
return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
var STRING_MAP_PROTO = Object.getPrototypeOf({});
/**
* @param {?} obj
* @return {?}
*/
function isStrictStringMap(obj) {
return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
}
/**
* @param {?} str
* @return {?}
*/
function utf8Encode(str) {
var /** @type {?} */ encoded = '';
for (var /** @type {?} */ index = 0; index < str.length; index++) {
var /** @type {?} */ codePoint = str.charCodeAt(index);
// decode surrogate
// see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) {
var /** @type {?} */ low = str.charCodeAt(index + 1);
if (low >= 0xdc00 && low <= 0xdfff) {
index++;
codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
}
}
if (codePoint <= 0x7f) {
encoded += String.fromCharCode(codePoint);
}
else if (codePoint <= 0x7ff) {
encoded += String.fromCharCode(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80);
}
else if (codePoint <= 0xffff) {
encoded += String.fromCharCode((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
}
else if (codePoint <= 0x1fffff) {
encoded += String.fromCharCode(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
}
}
return encoded;
}
/**
* @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
*/
// group 0: "[prop] or (event) or @trigger"
// group 1: "prop" from "[prop]"
// group 2: "event" from "(event)"
// group 3: "@trigger" from "@trigger"
var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
var CompileAnimationEntryMetadata = (function () {
/**
* @param {?=} name
* @param {?=} definitions
*/
function CompileAnimationEntryMetadata(name, definitions) {
if (name === void 0) { name = null; }
if (definitions === void 0) { definitions = null; }
this.name = name;
this.definitions = definitions;
}
return CompileAnimationEntryMetadata;
}());
/**
* @abstract
*/
var CompileAnimationStateMetadata = (function () {
function CompileAnimationStateMetadata() {
}
return CompileAnimationStateMetadata;
}());
var CompileAnimationStateDeclarationMetadata = (function (_super) {
__extends(CompileAnimationStateDeclarationMetadata, _super);
/**
* @param {?} stateNameExpr
* @param {?} styles
*/
function CompileAnimationStateDeclarationMetadata(stateNameExpr, styles) {
var _this = _super.call(this) || this;
_this.stateNameExpr = stateNameExpr;
_this.styles = styles;
return _this;
}
return CompileAnimationStateDeclarationMetadata;
}(CompileAnimationStateMetadata));
var CompileAnimationStateTransitionMetadata = (function (_super) {
__extends(CompileAnimationStateTransitionMetadata, _super);
/**
* @param {?} stateChangeExpr
* @param {?} steps
*/
function CompileAnimationStateTransitionMetadata(stateChangeExpr, steps) {
var _this = _super.call(this) || this;
_this.stateChangeExpr = stateChangeExpr;
_this.steps = steps;
return _this;
}
return CompileAnimationStateTransitionMetadata;
}(CompileAnimationStateMetadata));
/**
* @abstract
*/
var CompileAnimationMetadata = (function () {
function CompileAnimationMetadata() {
}
return CompileAnimationMetadata;
}());
var CompileAnimationKeyframesSequenceMetadata = (function (_super) {
__extends(CompileAnimationKeyframesSequenceMetadata, _super);
/**
* @param {?=} steps
*/
function CompileAnimationKeyframesSequenceMetadata(steps) {
if (steps === void 0) { steps = []; }
var _this = _super.call(this) || this;
_this.steps = steps;
return _this;
}
return CompileAnimationKeyframesSequenceMetadata;
}(CompileAnimationMetadata));
var CompileAnimationStyleMetadata = (function (_super) {
__extends(CompileAnimationStyleMetadata, _super);
/**
* @param {?} offset
* @param {?=} styles
*/
function CompileAnimationStyleMetadata(offset, styles) {
if (styles === void 0) { styles = null; }
var _this = _super.call(this) || this;
_this.offset = offset;
_this.styles = styles;
return _this;
}
return CompileAnimationStyleMetadata;
}(CompileAnimationMetadata));
var CompileAnimationAnimateMetadata = (function (_super) {
__extends(CompileAnimationAnimateMetadata, _super);
/**
* @param {?=} timings
* @param {?=} styles
*/
function CompileAnimationAnimateMetadata(timings, styles) {
if (timings === void 0) { timings = 0; }
if (styles === void 0) { styles = null; }
var _this = _super.call(this) || this;
_this.timings = timings;
_this.styles = styles;
return _this;
}
return CompileAnimationAnimateMetadata;
}(CompileAnimationMetadata));
/**
* @abstract
*/
var CompileAnimationWithStepsMetadata = (function (_super) {
__extends(CompileAnimationWithStepsMetadata, _super);
/**
* @param {?=} steps
*/
function CompileAnimationWithStepsMetadata(steps) {
if (steps === void 0) { steps = null; }
var _this = _super.call(this) || this;
_this.steps = steps;
return _this;
}
return CompileAnimationWithStepsMetadata;
}(CompileAnimationMetadata));
var CompileAnimationSequenceMetadata = (function (_super) {
__extends(CompileAnimationSequenceMetadata, _super);
/**
* @param {?=} steps
*/
function CompileAnimationSequenceMetadata(steps) {
if (steps === void 0) { steps = null; }
return _super.call(this, steps) || this;
}
return CompileAnimationSequenceMetadata;
}(CompileAnimationWithStepsMetadata));
var CompileAnimationGroupMetadata = (function (_super) {
__extends(CompileAnimationGroupMetadata, _super);
/**
* @param {?=} steps
*/
function CompileAnimationGroupMetadata(steps) {
if (steps === void 0) { steps = null; }
return _super.call(this, steps) || this;
}
return CompileAnimationGroupMetadata;
}(CompileAnimationWithStepsMetadata));
/**
* @param {?} name
* @return {?}
*/
function _sanitizeIdentifier(name) {
return name.replace(/\W/g, '_');
}
var _anonymousTypeIndex = 0;
/**
* @param {?} compileIdentifier
* @return {?}
*/
function identifierName(compileIdentifier) {
if (!compileIdentifier || !compileIdentifier.reference) {
return null;
}
var /** @type {?} */ ref = compileIdentifier.reference;
if (ref instanceof StaticSymbol) {
return ref.name;
}
if (ref['__anonymousType']) {
return ref['__anonymousType'];
}
var /** @type {?} */ identifier = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(ref);
if (identifier.indexOf('(') >= 0) {
// case: anonymous functions!
identifier = "anonymous_" + _anonymousTypeIndex++;
ref['__anonymousType'] = identifier;
}
else {
identifier = _sanitizeIdentifier(identifier);
}
return identifier;
}
/**
* @param {?} compileIdentifier
* @return {?}
*/
function identifierModuleUrl(compileIdentifier) {
var /** @type {?} */ ref = compileIdentifier.reference;
if (ref instanceof StaticSymbol) {
return ref.filePath;
}
return __WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */].importUri(ref);
}
/**
* @param {?} compType
* @param {?} embeddedTemplateIndex
* @return {?}
*/
function viewClassName(compType, embeddedTemplateIndex) {
return "View_" + identifierName({ reference: compType }) + "_" + embeddedTemplateIndex;
}
/**
* @param {?} compType
* @return {?}
*/
function rendererTypeName(compType) {
return "RenderType_" + identifierName({ reference: compType });
}
/**
* @param {?} compType
* @return {?}
*/
function hostViewClassName(compType) {
return "HostView_" + identifierName({ reference: compType });
}
/**
* @param {?} dirType
* @return {?}
*/
function dirWrapperClassName(dirType) {
return "Wrapper_" + identifierName({ reference: dirType });
}
/**
* @param {?} compType
* @return {?}
*/
function componentFactoryName(compType) {
return identifierName({ reference: compType }) + "NgFactory";
}
var CompileSummaryKind = {};
CompileSummaryKind.Pipe = 0;
CompileSummaryKind.Directive = 1;
CompileSummaryKind.NgModule = 2;
CompileSummaryKind.Injectable = 3;
CompileSummaryKind[CompileSummaryKind.Pipe] = "Pipe";
CompileSummaryKind[CompileSummaryKind.Directive] = "Directive";
CompileSummaryKind[CompileSummaryKind.NgModule] = "NgModule";
CompileSummaryKind[CompileSummaryKind.Injectable] = "Injectable";
/**
* @param {?} token
* @return {?}
*/
function tokenName(token) {
return token.value != null ? _sanitizeIdentifier(token.value) : identifierName(token.identifier);
}
/**
* @param {?} token
* @return {?}
*/
function tokenReference(token) {
if (token.identifier != null) {
return token.identifier.reference;
}
else {
return token.value;
}
}
/**
* Metadata about a stylesheet
*/
var CompileStylesheetMetadata = (function () {
/**
* @param {?=} __0
*/
function CompileStylesheetMetadata(_a) {
var _b = _a === void 0 ? {} : _a, moduleUrl = _b.moduleUrl, styles = _b.styles, styleUrls = _b.styleUrls;
this.moduleUrl = moduleUrl || null;
this.styles = _normalizeArray(styles);
this.styleUrls = _normalizeArray(styleUrls);
}
return CompileStylesheetMetadata;
}());
/**
* Metadata regarding compilation of a template.
*/
var CompileTemplateMetadata = (function () {
/**
* @param {?} __0
*/
function CompileTemplateMetadata(_a) {
var encapsulation = _a.encapsulation, template = _a.template, templateUrl = _a.templateUrl, styles = _a.styles, styleUrls = _a.styleUrls, externalStylesheets = _a.externalStylesheets, animations = _a.animations, ngContentSelectors = _a.ngContentSelectors, interpolation = _a.interpolation, isInline = _a.isInline;
this.encapsulation = encapsulation;
this.template = template;
this.templateUrl = templateUrl;
this.styles = _normalizeArray(styles);
this.styleUrls = _normalizeArray(styleUrls);
this.externalStylesheets = _normalizeArray(externalStylesheets);
this.animations = animations ? flatten(animations) : [];
this.ngContentSelectors = ngContentSelectors || [];
if (interpolation && interpolation.length != 2) {
throw new Error("'interpolation' should have a start and an end symbol.");
}
this.interpolation = interpolation;
this.isInline = isInline;
}
/**
* @return {?}
*/
CompileTemplateMetadata.prototype.toSummary = function () {
return {
animations: this.animations.map(function (anim) { return anim.name; }),
ngContentSelectors: this.ngContentSelectors,
encapsulation: this.encapsulation,
};
};
return CompileTemplateMetadata;
}());
/**
* Metadata regarding compilation of a directive.
*/
var CompileDirectiveMetadata = (function () {
/**
* @param {?} __0
*/
function CompileDirectiveMetadata(_a) {
var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, hostListeners = _a.hostListeners, hostProperties = _a.hostProperties, hostAttributes = _a.hostAttributes, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
this.isHost = !!isHost;
this.type = type;
this.isComponent = isComponent;
this.selector = selector;
this.exportAs = exportAs;
this.changeDetection = changeDetection;
this.inputs = inputs;
this.outputs = outputs;
this.hostListeners = hostListeners;
this.hostProperties = hostProperties;
this.hostAttributes = hostAttributes;
this.providers = _normalizeArray(providers);
this.viewProviders = _normalizeArray(viewProviders);
this.queries = _normalizeArray(queries);
this.viewQueries = _normalizeArray(viewQueries);
this.entryComponents = _normalizeArray(entryComponents);
this.template = template;
this.componentViewType = componentViewType;
this.rendererType = rendererType;
this.componentFactory = componentFactory;
}
/**
* @param {?} __0
* @return {?}
*/
CompileDirectiveMetadata.create = function (_a) {
var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, host = _a.host, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
var /** @type {?} */ hostListeners = {};
var /** @type {?} */ hostProperties = {};
var /** @type {?} */ hostAttributes = {};
if (host != null) {
Object.keys(host).forEach(function (key) {
var /** @type {?} */ value = host[key];
var /** @type {?} */ matches = key.match(HOST_REG_EXP);
if (matches === null) {
hostAttributes[key] = value;
}
else if (matches[1] != null) {
hostProperties[matches[1]] = value;
}
else if (matches[2] != null) {
hostListeners[matches[2]] = value;
}
});
}
var /** @type {?} */ inputsMap = {};
if (inputs != null) {
inputs.forEach(function (bindConfig) {
// canonical syntax: `dirProp: elProp`
// if there is no `:`, use dirProp = elProp
var /** @type {?} */ parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
inputsMap[parts[0]] = parts[1];
});
}
var /** @type {?} */ outputsMap = {};
if (outputs != null) {
outputs.forEach(function (bindConfig) {
// canonical syntax: `dirProp: elProp`
// if there is no `:`, use dirProp = elProp
var /** @type {?} */ parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
outputsMap[parts[0]] = parts[1];
});
}
return new CompileDirectiveMetadata({
isHost: isHost,
type: type,
isComponent: !!isComponent, selector: selector, exportAs: exportAs, changeDetection: changeDetection,
inputs: inputsMap,
outputs: outputsMap,
hostListeners: hostListeners,
hostProperties: hostProperties,
hostAttributes: hostAttributes,
providers: providers,
viewProviders: viewProviders,
queries: queries,
viewQueries: viewQueries,
entryComponents: entryComponents,
template: template,
componentViewType: componentViewType,
rendererType: rendererType,
componentFactory: componentFactory,
});
};
/**
* @return {?}
*/
CompileDirectiveMetadata.prototype.toSummary = function () {
return {
summaryKind: CompileSummaryKind.Directive,
type: this.type,
isComponent: this.isComponent,
selector: this.selector,
exportAs: this.exportAs,
inputs: this.inputs,
outputs: this.outputs,
hostListeners: this.hostListeners,
hostProperties: this.hostProperties,
hostAttributes: this.hostAttributes,
providers: this.providers,
viewProviders: this.viewProviders,
queries: this.queries,
viewQueries: this.viewQueries,
entryComponents: this.entryComponents,
changeDetection: this.changeDetection,
template: this.template && this.template.toSummary(),
componentViewType: this.componentViewType,
rendererType: this.rendererType,
componentFactory: this.componentFactory
};
};
return CompileDirectiveMetadata;
}());
/**
* Construct {\@link CompileDirectiveMetadata} from {\@link ComponentTypeMetadata} and a selector.
* @param {?} hostTypeReference
* @param {?} compMeta
* @param {?} hostViewType
* @return {?}
*/
function createHostComponentMeta(hostTypeReference, compMeta, hostViewType) {
var /** @type {?} */ template = CssSelector.parse(/** @type {?} */ ((compMeta.selector)))[0].getMatchingElementTemplate();
return CompileDirectiveMetadata.create({
isHost: true,
type: { reference: hostTypeReference, diDeps: [], lifecycleHooks: [] },
template: new CompileTemplateMetadata({
encapsulation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].None,
template: template,
templateUrl: '',
styles: [],
styleUrls: [],
ngContentSelectors: [],
animations: [],
isInline: true,
externalStylesheets: [],
interpolation: null
}),
exportAs: null,
changeDetection: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_4" /* ChangeDetectionStrategy */].Default,
inputs: [],
outputs: [],
host: {},
isComponent: true,
selector: '*',
providers: [],
viewProviders: [],
queries: [],
viewQueries: [],
componentViewType: hostViewType,
rendererType: { id: '__Host__', encapsulation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].None, styles: [], data: {} },
entryComponents: [],
componentFactory: null
});
}
var CompilePipeMetadata = (function () {
/**
* @param {?} __0
*/
function CompilePipeMetadata(_a) {
var type = _a.type, name = _a.name, pure = _a.pure;
this.type = type;
this.name = name;
this.pure = !!pure;
}
/**
* @return {?}
*/
CompilePipeMetadata.prototype.toSummary = function () {
return {
summaryKind: CompileSummaryKind.Pipe,
type: this.type,
name: this.name,
pure: this.pure
};
};
return CompilePipeMetadata;
}());
/**
* Metadata regarding compilation of a module.
*/
var CompileNgModuleMetadata = (function () {
/**
* @param {?} __0
*/
function CompileNgModuleMetadata(_a) {
var type = _a.type, providers = _a.providers, declaredDirectives = _a.declaredDirectives, exportedDirectives = _a.exportedDirectives, declaredPipes = _a.declaredPipes, exportedPipes = _a.exportedPipes, entryComponents = _a.entryComponents, bootstrapComponents = _a.bootstrapComponents, importedModules = _a.importedModules, exportedModules = _a.exportedModules, schemas = _a.schemas, transitiveModule = _a.transitiveModule, id = _a.id;
this.type = type || null;
this.declaredDirectives = _normalizeArray(declaredDirectives);
this.exportedDirectives = _normalizeArray(exportedDirectives);
this.declaredPipes = _normalizeArray(declaredPipes);
this.exportedPipes = _normalizeArray(exportedPipes);
this.providers = _normalizeArray(providers);
this.entryComponents = _normalizeArray(entryComponents);
this.bootstrapComponents = _normalizeArray(bootstrapComponents);
this.importedModules = _normalizeArray(importedModules);
this.exportedModules = _normalizeArray(exportedModules);
this.schemas = _normalizeArray(schemas);
this.id = id || null;
this.transitiveModule = transitiveModule || null;
}
/**
* @return {?}
*/
CompileNgModuleMetadata.prototype.toSummary = function () {
var /** @type {?} */ module = ((this.transitiveModule));
return {
summaryKind: CompileSummaryKind.NgModule,
type: this.type,
entryComponents: module.entryComponents,
providers: module.providers,
modules: module.modules,
exportedDirectives: module.exportedDirectives,
exportedPipes: module.exportedPipes
};
};
return CompileNgModuleMetadata;
}());
var TransitiveCompileNgModuleMetadata = (function () {
function TransitiveCompileNgModuleMetadata() {
this.directivesSet = new Set();
this.directives = [];
this.exportedDirectivesSet = new Set();
this.exportedDirectives = [];
this.pipesSet = new Set();
this.pipes = [];
this.exportedPipesSet = new Set();
this.exportedPipes = [];
this.modulesSet = new Set();
this.modules = [];
this.entryComponentsSet = new Set();
this.entryComponents = [];
this.providers = [];
}
/**
* @param {?} provider
* @param {?} module
* @return {?}
*/
TransitiveCompileNgModuleMetadata.prototype.addProvider = function (provider, module) {
this.providers.push({ provider: provider, module: module });
};
/**
* @param {?} id
* @return {?}
*/
TransitiveCompileNgModuleMetadata.prototype.addDirective = function (id) {
if (!this.directivesSet.has(id.reference)) {
this.directivesSet.add(id.reference);
this.directives.push(id);
}
};
/**
* @param {?} id
* @return {?}
*/
TransitiveCompileNgModuleMetadata.prototype.addExportedDirective = function (id) {
if (!this.exportedDirectivesSet.has(id.reference)) {
this.exportedDirectivesSet.add(id.reference);
this.exportedDirectives.push(id);
}
};
/**
* @param {?} id
* @return {?}
*/
TransitiveCompileNgModuleMetadata.prototype.addPipe = function (id) {
if (!this.pipesSet.has(id.reference)) {
this.pipesSet.add(id.reference);
this.pipes.push(id);
}
};
/**
* @param {?} id
* @return {?}
*/
TransitiveCompileNgModuleMetadata.prototype.addExportedPipe = function (id) {
if (!this.exportedPipesSet.has(id.reference)) {
this.exportedPipesSet.add(id.reference);
this.exportedPipes.push(id);
}
};
/**
* @param {?} id
* @return {?}
*/
TransitiveCompileNgModuleMetadata.prototype.addModule = function (id) {
if (!this.modulesSet.has(id.reference)) {
this.modulesSet.add(id.reference);
this.modules.push(id);
}
};
/**
* @param {?} ec
* @return {?}
*/
TransitiveCompileNgModuleMetadata.prototype.addEntryComponent = function (ec) {
if (!this.entryComponentsSet.has(ec.componentType)) {
this.entryComponentsSet.add(ec.componentType);
this.entryComponents.push(ec);
}
};
return TransitiveCompileNgModuleMetadata;
}());
/**
* @param {?} obj
* @return {?}
*/
function _normalizeArray(obj) {
return obj || [];
}
var ProviderMeta = (function () {
/**
* @param {?} token
* @param {?} __1
*/
function ProviderMeta(token, _a) {
var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
this.token = token;
this.useClass = useClass || null;
this.useValue = useValue;
this.useExisting = useExisting;
this.useFactory = useFactory || null;
this.dependencies = deps || null;
this.multi = !!multi;
}
return ProviderMeta;
}());
/**
* @template T
* @param {?} list
* @return {?}
*/
function flatten(list) {
return list.reduce(function (flat, item) {
var /** @type {?} */ flatItem = Array.isArray(item) ? flatten(item) : item;
return ((flat)).concat(flatItem);
}, []);
}
/**
* @param {?} url
* @return {?}
*/
function sourceUrl(url) {
// Note: We need 3 "/" so that ng shows up as a separate domain
// in the chrome dev tools.
return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
}
/**
* @param {?} ngModuleType
* @param {?} compMeta
* @param {?} templateMeta
* @return {?}
*/
function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
var /** @type {?} */ url;
if (templateMeta.isInline) {
if (compMeta.type.reference instanceof StaticSymbol) {
// Note: a .ts file might contain multiple components with inline templates,
// so we need to give them unique urls, as these will be used for sourcemaps.
url = compMeta.type.reference.filePath + "." + compMeta.type.reference.name + ".html";
}
else {
url = identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".html";
}
}
else {
url = ((templateMeta.templateUrl));
}
// always prepend ng:// to make angular resources easy to find and not clobber
// user resources.
return sourceUrl(url);
}
/**
* @param {?} meta
* @param {?} id
* @return {?}
*/
function sharedStylesheetJitUrl(meta, id) {
var /** @type {?} */ pathParts = ((meta.moduleUrl)).split(/\/\\/g);
var /** @type {?} */ baseName = pathParts[pathParts.length - 1];
return sourceUrl("css/" + id + baseName + ".ngstyle.js");
}
/**
* @param {?} moduleMeta
* @return {?}
*/
function ngModuleJitUrl(moduleMeta) {
return sourceUrl(identifierName(moduleMeta.type) + "/module.ngfactory.js");
}
/**
* @param {?} ngModuleType
* @param {?} compMeta
* @return {?}
*/
function templateJitUrl(ngModuleType, compMeta) {
return sourceUrl(identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".ngfactory.js");
}
/**
* @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
*/
var CompilerConfig = (function () {
/**
* @param {?=} __0
*/
function CompilerConfig(_a) {
var _b = _a === void 0 ? {} : _a, _c = _b.defaultEncapsulation, defaultEncapsulation = _c === void 0 ? __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].Emulated : _c, _d = _b.useJit, useJit = _d === void 0 ? true : _d, missingTranslation = _b.missingTranslation, enableLegacyTemplate = _b.enableLegacyTemplate;
this.defaultEncapsulation = defaultEncapsulation;
this.useJit = !!useJit;
this.missingTranslation = missingTranslation || null;
this.enableLegacyTemplate = enableLegacyTemplate !== false;
}
return CompilerConfig;
}());
/**
* @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
*/
var ParserError = (function () {
/**
* @param {?} message
* @param {?} input
* @param {?} errLocation
* @param {?=} ctxLocation
*/
function ParserError(message, input, errLocation, ctxLocation) {
this.input = input;
this.errLocation = errLocation;
this.ctxLocation = ctxLocation;
this.message = "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation;
}
return ParserError;
}());
var ParseSpan = (function () {
/**
* @param {?} start
* @param {?} end
*/
function ParseSpan(start, end) {
this.start = start;
this.end = end;
}
return ParseSpan;
}());
var AST = (function () {
/**
* @param {?} span
*/
function AST(span) {
this.span = span;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
AST.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return null;
};
/**
* @return {?}
*/
AST.prototype.toString = function () { return 'AST'; };
return AST;
}());
/**
* Represents a quoted expression of the form:
*
* quote = prefix `:` uninterpretedExpression
* prefix = identifier
* uninterpretedExpression = arbitrary string
*
* A quoted expression is meant to be pre-processed by an AST transformer that
* converts it into another AST that no longer contains quoted expressions.
* It is meant to allow third-party developers to extend Angular template
* expression language. The `uninterpretedExpression` part of the quote is
* therefore not interpreted by the Angular's own expression parser.
*/
var Quote = (function (_super) {
__extends(Quote, _super);
/**
* @param {?} span
* @param {?} prefix
* @param {?} uninterpretedExpression
* @param {?} location
*/
function Quote(span, prefix, uninterpretedExpression, location) {
var _this = _super.call(this, span) || this;
_this.prefix = prefix;
_this.uninterpretedExpression = uninterpretedExpression;
_this.location = location;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Quote.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitQuote(this, context);
};
/**
* @return {?}
*/
Quote.prototype.toString = function () { return 'Quote'; };
return Quote;
}(AST));
var EmptyExpr = (function (_super) {
__extends(EmptyExpr, _super);
function EmptyExpr() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
EmptyExpr.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
// do nothing
};
return EmptyExpr;
}(AST));
var ImplicitReceiver = (function (_super) {
__extends(ImplicitReceiver, _super);
function ImplicitReceiver() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
ImplicitReceiver.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitImplicitReceiver(this, context);
};
return ImplicitReceiver;
}(AST));
/**
* Multiple expressions separated by a semicolon.
*/
var Chain = (function (_super) {
__extends(Chain, _super);
/**
* @param {?} span
* @param {?} expressions
*/
function Chain(span, expressions) {
var _this = _super.call(this, span) || this;
_this.expressions = expressions;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Chain.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitChain(this, context);
};
return Chain;
}(AST));
var Conditional = (function (_super) {
__extends(Conditional, _super);
/**
* @param {?} span
* @param {?} condition
* @param {?} trueExp
* @param {?} falseExp
*/
function Conditional(span, condition, trueExp, falseExp) {
var _this = _super.call(this, span) || this;
_this.condition = condition;
_this.trueExp = trueExp;
_this.falseExp = falseExp;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Conditional.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitConditional(this, context);
};
return Conditional;
}(AST));
var PropertyRead = (function (_super) {
__extends(PropertyRead, _super);
/**
* @param {?} span
* @param {?} receiver
* @param {?} name
*/
function PropertyRead(span, receiver, name) {
var _this = _super.call(this, span) || this;
_this.receiver = receiver;
_this.name = name;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
PropertyRead.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitPropertyRead(this, context);
};
return PropertyRead;
}(AST));
var PropertyWrite = (function (_super) {
__extends(PropertyWrite, _super);
/**
* @param {?} span
* @param {?} receiver
* @param {?} name
* @param {?} value
*/
function PropertyWrite(span, receiver, name, value) {
var _this = _super.call(this, span) || this;
_this.receiver = receiver;
_this.name = name;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
PropertyWrite.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitPropertyWrite(this, context);
};
return PropertyWrite;
}(AST));
var SafePropertyRead = (function (_super) {
__extends(SafePropertyRead, _super);
/**
* @param {?} span
* @param {?} receiver
* @param {?} name
*/
function SafePropertyRead(span, receiver, name) {
var _this = _super.call(this, span) || this;
_this.receiver = receiver;
_this.name = name;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
SafePropertyRead.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitSafePropertyRead(this, context);
};
return SafePropertyRead;
}(AST));
var KeyedRead = (function (_super) {
__extends(KeyedRead, _super);
/**
* @param {?} span
* @param {?} obj
* @param {?} key
*/
function KeyedRead(span, obj, key) {
var _this = _super.call(this, span) || this;
_this.obj = obj;
_this.key = key;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
KeyedRead.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitKeyedRead(this, context);
};
return KeyedRead;
}(AST));
var KeyedWrite = (function (_super) {
__extends(KeyedWrite, _super);
/**
* @param {?} span
* @param {?} obj
* @param {?} key
* @param {?} value
*/
function KeyedWrite(span, obj, key, value) {
var _this = _super.call(this, span) || this;
_this.obj = obj;
_this.key = key;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
KeyedWrite.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitKeyedWrite(this, context);
};
return KeyedWrite;
}(AST));
var BindingPipe = (function (_super) {
__extends(BindingPipe, _super);
/**
* @param {?} span
* @param {?} exp
* @param {?} name
* @param {?} args
*/
function BindingPipe(span, exp, name, args) {
var _this = _super.call(this, span) || this;
_this.exp = exp;
_this.name = name;
_this.args = args;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
BindingPipe.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitPipe(this, context);
};
return BindingPipe;
}(AST));
var LiteralPrimitive = (function (_super) {
__extends(LiteralPrimitive, _super);
/**
* @param {?} span
* @param {?} value
*/
function LiteralPrimitive(span, value) {
var _this = _super.call(this, span) || this;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
LiteralPrimitive.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitLiteralPrimitive(this, context);
};
return LiteralPrimitive;
}(AST));
var LiteralArray = (function (_super) {
__extends(LiteralArray, _super);
/**
* @param {?} span
* @param {?} expressions
*/
function LiteralArray(span, expressions) {
var _this = _super.call(this, span) || this;
_this.expressions = expressions;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
LiteralArray.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitLiteralArray(this, context);
};
return LiteralArray;
}(AST));
var LiteralMap = (function (_super) {
__extends(LiteralMap, _super);
/**
* @param {?} span
* @param {?} keys
* @param {?} values
*/
function LiteralMap(span, keys, values) {
var _this = _super.call(this, span) || this;
_this.keys = keys;
_this.values = values;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
LiteralMap.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitLiteralMap(this, context);
};
return LiteralMap;
}(AST));
var Interpolation = (function (_super) {
__extends(Interpolation, _super);
/**
* @param {?} span
* @param {?} strings
* @param {?} expressions
*/
function Interpolation(span, strings, expressions) {
var _this = _super.call(this, span) || this;
_this.strings = strings;
_this.expressions = expressions;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Interpolation.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitInterpolation(this, context);
};
return Interpolation;
}(AST));
var Binary = (function (_super) {
__extends(Binary, _super);
/**
* @param {?} span
* @param {?} operation
* @param {?} left
* @param {?} right
*/
function Binary(span, operation, left, right) {
var _this = _super.call(this, span) || this;
_this.operation = operation;
_this.left = left;
_this.right = right;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Binary.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitBinary(this, context);
};
return Binary;
}(AST));
var PrefixNot = (function (_super) {
__extends(PrefixNot, _super);
/**
* @param {?} span
* @param {?} expression
*/
function PrefixNot(span, expression) {
var _this = _super.call(this, span) || this;
_this.expression = expression;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
PrefixNot.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitPrefixNot(this, context);
};
return PrefixNot;
}(AST));
var MethodCall = (function (_super) {
__extends(MethodCall, _super);
/**
* @param {?} span
* @param {?} receiver
* @param {?} name
* @param {?} args
*/
function MethodCall(span, receiver, name, args) {
var _this = _super.call(this, span) || this;
_this.receiver = receiver;
_this.name = name;
_this.args = args;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
MethodCall.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitMethodCall(this, context);
};
return MethodCall;
}(AST));
var SafeMethodCall = (function (_super) {
__extends(SafeMethodCall, _super);
/**
* @param {?} span
* @param {?} receiver
* @param {?} name
* @param {?} args
*/
function SafeMethodCall(span, receiver, name, args) {
var _this = _super.call(this, span) || this;
_this.receiver = receiver;
_this.name = name;
_this.args = args;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
SafeMethodCall.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitSafeMethodCall(this, context);
};
return SafeMethodCall;
}(AST));
var FunctionCall = (function (_super) {
__extends(FunctionCall, _super);
/**
* @param {?} span
* @param {?} target
* @param {?} args
*/
function FunctionCall(span, target, args) {
var _this = _super.call(this, span) || this;
_this.target = target;
_this.args = args;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
FunctionCall.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return visitor.visitFunctionCall(this, context);
};
return FunctionCall;
}(AST));
var ASTWithSource = (function (_super) {
__extends(ASTWithSource, _super);
/**
* @param {?} ast
* @param {?} source
* @param {?} location
* @param {?} errors
*/
function ASTWithSource(ast, source, location, errors) {
var _this = _super.call(this, new ParseSpan(0, source == null ? 0 : source.length)) || this;
_this.ast = ast;
_this.source = source;
_this.location = location;
_this.errors = errors;
return _this;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
ASTWithSource.prototype.visit = function (visitor, context) {
if (context === void 0) { context = null; }
return this.ast.visit(visitor, context);
};
/**
* @return {?}
*/
ASTWithSource.prototype.toString = function () { return this.source + " in " + this.location; };
return ASTWithSource;
}(AST));
var TemplateBinding = (function () {
/**
* @param {?} span
* @param {?} key
* @param {?} keyIsVar
* @param {?} name
* @param {?} expression
*/
function TemplateBinding(span, key, keyIsVar, name, expression) {
this.span = span;
this.key = key;
this.keyIsVar = keyIsVar;
this.name = name;
this.expression = expression;
}
return TemplateBinding;
}());
var RecursiveAstVisitor = (function () {
function RecursiveAstVisitor() {
}
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitBinary = function (ast, context) {
ast.left.visit(this);
ast.right.visit(this);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitChain = function (ast, context) { return this.visitAll(ast.expressions, context); };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitConditional = function (ast, context) {
ast.condition.visit(this);
ast.trueExp.visit(this);
ast.falseExp.visit(this);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitPipe = function (ast, context) {
ast.exp.visit(this);
this.visitAll(ast.args, context);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitFunctionCall = function (ast, context) {
((ast.target)).visit(this);
this.visitAll(ast.args, context);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { return null; };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitInterpolation = function (ast, context) {
return this.visitAll(ast.expressions, context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitKeyedRead = function (ast, context) {
ast.obj.visit(this);
ast.key.visit(this);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast, context) {
ast.obj.visit(this);
ast.key.visit(this);
ast.value.visit(this);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitLiteralArray = function (ast, context) {
return this.visitAll(ast.expressions, context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitLiteralMap = function (ast, context) { return this.visitAll(ast.values, context); };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { return null; };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitMethodCall = function (ast, context) {
ast.receiver.visit(this);
return this.visitAll(ast.args, context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitPrefixNot = function (ast, context) {
ast.expression.visit(this);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitPropertyRead = function (ast, context) {
ast.receiver.visit(this);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast, context) {
ast.receiver.visit(this);
ast.value.visit(this);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast, context) {
ast.receiver.visit(this);
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast, context) {
ast.receiver.visit(this);
return this.visitAll(ast.args, context);
};
/**
* @param {?} asts
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitAll = function (asts, context) {
var _this = this;
asts.forEach(function (ast) { return ast.visit(_this, context); });
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor.prototype.visitQuote = function (ast, context) { return null; };
return RecursiveAstVisitor;
}());
var AstTransformer = (function () {
function AstTransformer() {
}
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitInterpolation = function (ast, context) {
return new Interpolation(ast.span, ast.strings, this.visitAll(ast.expressions));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitLiteralPrimitive = function (ast, context) {
return new LiteralPrimitive(ast.span, ast.value);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitPropertyRead = function (ast, context) {
return new PropertyRead(ast.span, ast.receiver.visit(this), ast.name);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitPropertyWrite = function (ast, context) {
return new PropertyWrite(ast.span, ast.receiver.visit(this), ast.name, ast.value.visit(this));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitSafePropertyRead = function (ast, context) {
return new SafePropertyRead(ast.span, ast.receiver.visit(this), ast.name);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitMethodCall = function (ast, context) {
return new MethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitSafeMethodCall = function (ast, context) {
return new SafeMethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitFunctionCall = function (ast, context) {
return new FunctionCall(ast.span, /** @type {?} */ ((ast.target)).visit(this), this.visitAll(ast.args));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitLiteralArray = function (ast, context) {
return new LiteralArray(ast.span, this.visitAll(ast.expressions));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitLiteralMap = function (ast, context) {
return new LiteralMap(ast.span, ast.keys, this.visitAll(ast.values));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitBinary = function (ast, context) {
return new Binary(ast.span, ast.operation, ast.left.visit(this), ast.right.visit(this));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitPrefixNot = function (ast, context) {
return new PrefixNot(ast.span, ast.expression.visit(this));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitConditional = function (ast, context) {
return new Conditional(ast.span, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitPipe = function (ast, context) {
return new BindingPipe(ast.span, ast.exp.visit(this), ast.name, this.visitAll(ast.args));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitKeyedRead = function (ast, context) {
return new KeyedRead(ast.span, ast.obj.visit(this), ast.key.visit(this));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitKeyedWrite = function (ast, context) {
return new KeyedWrite(ast.span, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
};
/**
* @param {?} asts
* @return {?}
*/
AstTransformer.prototype.visitAll = function (asts) {
var /** @type {?} */ res = new Array(asts.length);
for (var /** @type {?} */ i = 0; i < asts.length; ++i) {
res[i] = asts[i].visit(this);
}
return res;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitChain = function (ast, context) {
return new Chain(ast.span, this.visitAll(ast.expressions));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer.prototype.visitQuote = function (ast, context) {
return new Quote(ast.span, ast.prefix, ast.uninterpretedExpression, ast.location);
};
return AstTransformer;
}());
/**
* @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
*/
var $EOF = 0;
var $TAB = 9;
var $LF = 10;
var $VTAB = 11;
var $FF = 12;
var $CR = 13;
var $SPACE = 32;
var $BANG = 33;
var $DQ = 34;
var $HASH = 35;
var $$ = 36;
var $PERCENT = 37;
var $AMPERSAND = 38;
var $SQ = 39;
var $LPAREN = 40;
var $RPAREN = 41;
var $STAR = 42;
var $PLUS = 43;
var $COMMA = 44;
var $MINUS = 45;
var $PERIOD = 46;
var $SLASH = 47;
var $COLON = 58;
var $SEMICOLON = 59;
var $LT = 60;
var $EQ = 61;
var $GT = 62;
var $QUESTION = 63;
var $0 = 48;
var $9 = 57;
var $A = 65;
var $E = 69;
var $F = 70;
var $X = 88;
var $Z = 90;
var $LBRACKET = 91;
var $BACKSLASH = 92;
var $RBRACKET = 93;
var $CARET = 94;
var $_ = 95;
var $a = 97;
var $e = 101;
var $f = 102;
var $n = 110;
var $r = 114;
var $t = 116;
var $u = 117;
var $v = 118;
var $x = 120;
var $z = 122;
var $LBRACE = 123;
var $BAR = 124;
var $RBRACE = 125;
var $NBSP = 160;
var $BT = 96;
/**
* @param {?} code
* @return {?}
*/
function isWhitespace(code) {
return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
}
/**
* @param {?} code
* @return {?}
*/
function isDigit(code) {
return $0 <= code && code <= $9;
}
/**
* @param {?} code
* @return {?}
*/
function isAsciiLetter(code) {
return code >= $a && code <= $z || code >= $A && code <= $Z;
}
/**
* @param {?} code
* @return {?}
*/
function isAsciiHexDigit(code) {
return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code);
}
/**
* A replacement for \@Injectable to be used in the compiler, so that
* we don't try to evaluate the metadata in the compiler during AoT.
* This decorator is enough to make the compiler work with the ReflectiveInjector though.
* \@Annotation
* @return {?}
*/
function CompilerInjectable() {
return function (x) { return x; };
}
/**
* @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
*/
/**
* @param {?} identifier
* @param {?} value
* @return {?}
*/
function assertArrayOfStrings(identifier, value) {
if (!__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["E" /* isDevMode */])() || value == null) {
return;
}
if (!Array.isArray(value)) {
throw new Error("Expected '" + identifier + "' to be an array of strings.");
}
for (var /** @type {?} */ i = 0; i < value.length; i += 1) {
if (typeof value[i] !== 'string') {
throw new Error("Expected '" + identifier + "' to be an array of strings.");
}
}
}
var INTERPOLATION_BLACKLIST_REGEXPS = [
/^\s*$/,
/[<>]/,
/^[{}]$/,
/&(#|[a-z])/i,
/^\/\//,
];
/**
* @param {?} identifier
* @param {?} value
* @return {?}
*/
function assertInterpolationSymbols(identifier, value) {
if (value != null && !(Array.isArray(value) && value.length == 2)) {
throw new Error("Expected '" + identifier + "' to be an array, [start, end].");
}
else if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["E" /* isDevMode */])() && value != null) {
var /** @type {?} */ start_1 = (value[0]);
var /** @type {?} */ end_1 = (value[1]);
// black list checking
INTERPOLATION_BLACKLIST_REGEXPS.forEach(function (regexp) {
if (regexp.test(start_1) || regexp.test(end_1)) {
throw new Error("['" + start_1 + "', '" + end_1 + "'] contains unusable interpolation symbol.");
}
});
}
}
/**
* @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
*/
var InterpolationConfig = (function () {
/**
* @param {?} start
* @param {?} end
*/
function InterpolationConfig(start, end) {
this.start = start;
this.end = end;
}
/**
* @param {?} markers
* @return {?}
*/
InterpolationConfig.fromArray = function (markers) {
if (!markers) {
return DEFAULT_INTERPOLATION_CONFIG;
}
assertInterpolationSymbols('interpolation', markers);
return new InterpolationConfig(markers[0], markers[1]);
};
;
return InterpolationConfig;
}());
var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}');
/**
* @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
*/
var TokenType = {};
TokenType.Character = 0;
TokenType.Identifier = 1;
TokenType.Keyword = 2;
TokenType.String = 3;
TokenType.Operator = 4;
TokenType.Number = 5;
TokenType.Error = 6;
TokenType[TokenType.Character] = "Character";
TokenType[TokenType.Identifier] = "Identifier";
TokenType[TokenType.Keyword] = "Keyword";
TokenType[TokenType.String] = "String";
TokenType[TokenType.Operator] = "Operator";
TokenType[TokenType.Number] = "Number";
TokenType[TokenType.Error] = "Error";
var KEYWORDS = ['var', 'let', 'as', 'null', 'undefined', 'true', 'false', 'if', 'else', 'this'];
var Lexer = (function () {
function Lexer() {
}
/**
* @param {?} text
* @return {?}
*/
Lexer.prototype.tokenize = function (text) {
var /** @type {?} */ scanner = new _Scanner(text);
var /** @type {?} */ tokens = [];
var /** @type {?} */ token = scanner.scanToken();
while (token != null) {
tokens.push(token);
token = scanner.scanToken();
}
return tokens;
};
return Lexer;
}());
Lexer.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
Lexer.ctorParameters = function () { return []; };
var Token = (function () {
/**
* @param {?} index
* @param {?} type
* @param {?} numValue
* @param {?} strValue
*/
function Token(index, type, numValue, strValue) {
this.index = index;
this.type = type;
this.numValue = numValue;
this.strValue = strValue;
}
/**
* @param {?} code
* @return {?}
*/
Token.prototype.isCharacter = function (code) {
return this.type == TokenType.Character && this.numValue == code;
};
/**
* @return {?}
*/
Token.prototype.isNumber = function () { return this.type == TokenType.Number; };
/**
* @return {?}
*/
Token.prototype.isString = function () { return this.type == TokenType.String; };
/**
* @param {?} operater
* @return {?}
*/
Token.prototype.isOperator = function (operater) {
return this.type == TokenType.Operator && this.strValue == operater;
};
/**
* @return {?}
*/
Token.prototype.isIdentifier = function () { return this.type == TokenType.Identifier; };
/**
* @return {?}
*/
Token.prototype.isKeyword = function () { return this.type == TokenType.Keyword; };
/**
* @return {?}
*/
Token.prototype.isKeywordLet = function () { return this.type == TokenType.Keyword && this.strValue == 'let'; };
/**
* @return {?}
*/
Token.prototype.isKeywordAs = function () { return this.type == TokenType.Keyword && this.strValue == 'as'; };
/**
* @return {?}
*/
Token.prototype.isKeywordNull = function () { return this.type == TokenType.Keyword && this.strValue == 'null'; };
/**
* @return {?}
*/
Token.prototype.isKeywordUndefined = function () {
return this.type == TokenType.Keyword && this.strValue == 'undefined';
};
/**
* @return {?}
*/
Token.prototype.isKeywordTrue = function () { return this.type == TokenType.Keyword && this.strValue == 'true'; };
/**
* @return {?}
*/
Token.prototype.isKeywordFalse = function () { return this.type == TokenType.Keyword && this.strValue == 'false'; };
/**
* @return {?}
*/
Token.prototype.isKeywordThis = function () { return this.type == TokenType.Keyword && this.strValue == 'this'; };
/**
* @return {?}
*/
Token.prototype.isError = function () { return this.type == TokenType.Error; };
/**
* @return {?}
*/
Token.prototype.toNumber = function () { return this.type == TokenType.Number ? this.numValue : -1; };
/**
* @return {?}
*/
Token.prototype.toString = function () {
switch (this.type) {
case TokenType.Character:
case TokenType.Identifier:
case TokenType.Keyword:
case TokenType.Operator:
case TokenType.String:
case TokenType.Error:
return this.strValue;
case TokenType.Number:
return this.numValue.toString();
default:
return null;
}
};
return Token;
}());
/**
* @param {?} index
* @param {?} code
* @return {?}
*/
function newCharacterToken(index, code) {
return new Token(index, TokenType.Character, code, String.fromCharCode(code));
}
/**
* @param {?} index
* @param {?} text
* @return {?}
*/
function newIdentifierToken(index, text) {
return new Token(index, TokenType.Identifier, 0, text);
}
/**
* @param {?} index
* @param {?} text
* @return {?}
*/
function newKeywordToken(index, text) {
return new Token(index, TokenType.Keyword, 0, text);
}
/**
* @param {?} index
* @param {?} text
* @return {?}
*/
function newOperatorToken(index, text) {
return new Token(index, TokenType.Operator, 0, text);
}
/**
* @param {?} index
* @param {?} text
* @return {?}
*/
function newStringToken(index, text) {
return new Token(index, TokenType.String, 0, text);
}
/**
* @param {?} index
* @param {?} n
* @return {?}
*/
function newNumberToken(index, n) {
return new Token(index, TokenType.Number, n, '');
}
/**
* @param {?} index
* @param {?} message
* @return {?}
*/
function newErrorToken(index, message) {
return new Token(index, TokenType.Error, 0, message);
}
var EOF = new Token(-1, TokenType.Character, 0, '');
var _Scanner = (function () {
/**
* @param {?} input
*/
function _Scanner(input) {
this.input = input;
this.peek = 0;
this.index = -1;
this.length = input.length;
this.advance();
}
/**
* @return {?}
*/
_Scanner.prototype.advance = function () {
this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
};
/**
* @return {?}
*/
_Scanner.prototype.scanToken = function () {
var /** @type {?} */ input = this.input, /** @type {?} */ length = this.length;
var /** @type {?} */ peek = this.peek, /** @type {?} */ index = this.index;
// Skip whitespace.
while (peek <= $SPACE) {
if (++index >= length) {
peek = $EOF;
break;
}
else {
peek = input.charCodeAt(index);
}
}
this.peek = peek;
this.index = index;
if (index >= length) {
return null;
}
// Handle identifiers and numbers.
if (isIdentifierStart(peek))
return this.scanIdentifier();
if (isDigit(peek))
return this.scanNumber(index);
var /** @type {?} */ start = index;
switch (peek) {
case $PERIOD:
this.advance();
return isDigit(this.peek) ? this.scanNumber(start) :
newCharacterToken(start, $PERIOD);
case $LPAREN:
case $RPAREN:
case $LBRACE:
case $RBRACE:
case $LBRACKET:
case $RBRACKET:
case $COMMA:
case $COLON:
case $SEMICOLON:
return this.scanCharacter(start, peek);
case $SQ:
case $DQ:
return this.scanString();
case $HASH:
case $PLUS:
case $MINUS:
case $STAR:
case $SLASH:
case $PERCENT:
case $CARET:
return this.scanOperator(start, String.fromCharCode(peek));
case $QUESTION:
return this.scanComplexOperator(start, '?', $PERIOD, '.');
case $LT:
case $GT:
return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=');
case $BANG:
case $EQ:
return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=', $EQ, '=');
case $AMPERSAND:
return this.scanComplexOperator(start, '&', $AMPERSAND, '&');
case $BAR:
return this.scanComplexOperator(start, '|', $BAR, '|');
case $NBSP:
while (isWhitespace(this.peek))
this.advance();
return this.scanToken();
}
this.advance();
return this.error("Unexpected character [" + String.fromCharCode(peek) + "]", 0);
};
/**
* @param {?} start
* @param {?} code
* @return {?}
*/
_Scanner.prototype.scanCharacter = function (start, code) {
this.advance();
return newCharacterToken(start, code);
};
/**
* @param {?} start
* @param {?} str
* @return {?}
*/
_Scanner.prototype.scanOperator = function (start, str) {
this.advance();
return newOperatorToken(start, str);
};
/**
* Tokenize a 2/3 char long operator
*
* @param {?} start start index in the expression
* @param {?} one first symbol (always part of the operator)
* @param {?} twoCode code point for the second symbol
* @param {?} two second symbol (part of the operator when the second code point matches)
* @param {?=} threeCode code point for the third symbol
* @param {?=} three third symbol (part of the operator when provided and matches source expression)
* @return {?}
*/
_Scanner.prototype.scanComplexOperator = function (start, one, twoCode, two, threeCode, three) {
this.advance();
var /** @type {?} */ str = one;
if (this.peek == twoCode) {
this.advance();
str += two;
}
if (threeCode != null && this.peek == threeCode) {
this.advance();
str += three;
}
return newOperatorToken(start, str);
};
/**
* @return {?}
*/
_Scanner.prototype.scanIdentifier = function () {
var /** @type {?} */ start = this.index;
this.advance();
while (isIdentifierPart(this.peek))
this.advance();
var /** @type {?} */ str = this.input.substring(start, this.index);
return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) :
newIdentifierToken(start, str);
};
/**
* @param {?} start
* @return {?}
*/
_Scanner.prototype.scanNumber = function (start) {
var /** @type {?} */ simple = (this.index === start);
this.advance(); // Skip initial digit.
while (true) {
if (isDigit(this.peek)) {
}
else if (this.peek == $PERIOD) {
simple = false;
}
else if (isExponentStart(this.peek)) {
this.advance();
if (isExponentSign(this.peek))
this.advance();
if (!isDigit(this.peek))
return this.error('Invalid exponent', -1);
simple = false;
}
else {
break;
}
this.advance();
}
var /** @type {?} */ str = this.input.substring(start, this.index);
var /** @type {?} */ value = simple ? parseIntAutoRadix(str) : parseFloat(str);
return newNumberToken(start, value);
};
/**
* @return {?}
*/
_Scanner.prototype.scanString = function () {
var /** @type {?} */ start = this.index;
var /** @type {?} */ quote = this.peek;
this.advance(); // Skip initial quote.
var /** @type {?} */ buffer = '';
var /** @type {?} */ marker = this.index;
var /** @type {?} */ input = this.input;
while (this.peek != quote) {
if (this.peek == $BACKSLASH) {
buffer += input.substring(marker, this.index);
this.advance();
var /** @type {?} */ unescapedCode = void 0;
// Workaround for TS2.1-introduced type strictness
this.peek = this.peek;
if (this.peek == $u) {
// 4 character hex code for unicode character.
var /** @type {?} */ hex = input.substring(this.index + 1, this.index + 5);
if (/^[0-9a-f]+$/i.test(hex)) {
unescapedCode = parseInt(hex, 16);
}
else {
return this.error("Invalid unicode escape [\\u" + hex + "]", 0);
}
for (var /** @type {?} */ i = 0; i < 5; i++) {
this.advance();
}
}
else {
unescapedCode = unescape(this.peek);
this.advance();
}
buffer += String.fromCharCode(unescapedCode);
marker = this.index;
}
else if (this.peek == $EOF) {
return this.error('Unterminated quote', 0);
}
else {
this.advance();
}
}
var /** @type {?} */ last = input.substring(marker, this.index);
this.advance(); // Skip terminating quote.
return newStringToken(start, buffer + last);
};
/**
* @param {?} message
* @param {?} offset
* @return {?}
*/
_Scanner.prototype.error = function (message, offset) {
var /** @type {?} */ position = this.index + offset;
return newErrorToken(position, "Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]");
};
return _Scanner;
}());
/**
* @param {?} code
* @return {?}
*/
function isIdentifierStart(code) {
return ($a <= code && code <= $z) || ($A <= code && code <= $Z) ||
(code == $_) || (code == $$);
}
/**
* @param {?} input
* @return {?}
*/
function isIdentifier(input) {
if (input.length == 0)
return false;
var /** @type {?} */ scanner = new _Scanner(input);
if (!isIdentifierStart(scanner.peek))
return false;
scanner.advance();
while (scanner.peek !== $EOF) {
if (!isIdentifierPart(scanner.peek))
return false;
scanner.advance();
}
return true;
}
/**
* @param {?} code
* @return {?}
*/
function isIdentifierPart(code) {
return isAsciiLetter(code) || isDigit(code) || (code == $_) ||
(code == $$);
}
/**
* @param {?} code
* @return {?}
*/
function isExponentStart(code) {
return code == $e || code == $E;
}
/**
* @param {?} code
* @return {?}
*/
function isExponentSign(code) {
return code == $MINUS || code == $PLUS;
}
/**
* @param {?} code
* @return {?}
*/
function isQuote(code) {
return code === $SQ || code === $DQ || code === $BT;
}
/**
* @param {?} code
* @return {?}
*/
function unescape(code) {
switch (code) {
case $n:
return $LF;
case $f:
return $FF;
case $r:
return $CR;
case $t:
return $TAB;
case $v:
return $VTAB;
default:
return code;
}
}
/**
* @param {?} text
* @return {?}
*/
function parseIntAutoRadix(text) {
var /** @type {?} */ result = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
}
/**
* @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
*/
var SplitInterpolation = (function () {
/**
* @param {?} strings
* @param {?} expressions
* @param {?} offsets
*/
function SplitInterpolation(strings, expressions, offsets) {
this.strings = strings;
this.expressions = expressions;
this.offsets = offsets;
}
return SplitInterpolation;
}());
var TemplateBindingParseResult = (function () {
/**
* @param {?} templateBindings
* @param {?} warnings
* @param {?} errors
*/
function TemplateBindingParseResult(templateBindings, warnings, errors) {
this.templateBindings = templateBindings;
this.warnings = warnings;
this.errors = errors;
}
return TemplateBindingParseResult;
}());
/**
* @param {?} config
* @return {?}
*/
function _createInterpolateRegExp(config) {
var /** @type {?} */ pattern = escapeRegExp(config.start) + '([\\s\\S]*?)' + escapeRegExp(config.end);
return new RegExp(pattern, 'g');
}
var Parser = (function () {
/**
* @param {?} _lexer
*/
function Parser(_lexer) {
this._lexer = _lexer;
this.errors = [];
}
/**
* @param {?} input
* @param {?} location
* @param {?=} interpolationConfig
* @return {?}
*/
Parser.prototype.parseAction = function (input, location, interpolationConfig) {
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
this._checkNoInterpolation(input, location, interpolationConfig);
var /** @type {?} */ sourceToLex = this._stripComments(input);
var /** @type {?} */ tokens = this._lexer.tokenize(this._stripComments(input));
var /** @type {?} */ ast = new _ParseAST(input, location, tokens, sourceToLex.length, true, this.errors, input.length - sourceToLex.length)
.parseChain();
return new ASTWithSource(ast, input, location, this.errors);
};
/**
* @param {?} input
* @param {?} location
* @param {?=} interpolationConfig
* @return {?}
*/
Parser.prototype.parseBinding = function (input, location, interpolationConfig) {
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
var /** @type {?} */ ast = this._parseBindingAst(input, location, interpolationConfig);
return new ASTWithSource(ast, input, location, this.errors);
};
/**
* @param {?} input
* @param {?} location
* @param {?=} interpolationConfig
* @return {?}
*/
Parser.prototype.parseSimpleBinding = function (input, location, interpolationConfig) {
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
var /** @type {?} */ ast = this._parseBindingAst(input, location, interpolationConfig);
var /** @type {?} */ errors = SimpleExpressionChecker.check(ast);
if (errors.length > 0) {
this._reportError("Host binding expression cannot contain " + errors.join(' '), input, location);
}
return new ASTWithSource(ast, input, location, this.errors);
};
/**
* @param {?} message
* @param {?} input
* @param {?} errLocation
* @param {?=} ctxLocation
* @return {?}
*/
Parser.prototype._reportError = function (message, input, errLocation, ctxLocation) {
this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
};
/**
* @param {?} input
* @param {?} location
* @param {?} interpolationConfig
* @return {?}
*/
Parser.prototype._parseBindingAst = function (input, location, interpolationConfig) {
// Quotes expressions use 3rd-party expression language. We don't want to use
// our lexer or parser for that, so we check for that ahead of time.
var /** @type {?} */ quote = this._parseQuote(input, location);
if (quote != null) {
return quote;
}
this._checkNoInterpolation(input, location, interpolationConfig);
var /** @type {?} */ sourceToLex = this._stripComments(input);
var /** @type {?} */ tokens = this._lexer.tokenize(sourceToLex);
return new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, input.length - sourceToLex.length)
.parseChain();
};
/**
* @param {?} input
* @param {?} location
* @return {?}
*/
Parser.prototype._parseQuote = function (input, location) {
if (input == null)
return null;
var /** @type {?} */ prefixSeparatorIndex = input.indexOf(':');
if (prefixSeparatorIndex == -1)
return null;
var /** @type {?} */ prefix = input.substring(0, prefixSeparatorIndex).trim();
if (!isIdentifier(prefix))
return null;
var /** @type {?} */ uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location);
};
/**
* @param {?} prefixToken
* @param {?} input
* @param {?} location
* @return {?}
*/
Parser.prototype.parseTemplateBindings = function (prefixToken, input, location) {
var /** @type {?} */ tokens = this._lexer.tokenize(input);
if (prefixToken) {
// Prefix the tokens with the tokens from prefixToken but have them take no space (0 index).
var /** @type {?} */ prefixTokens = this._lexer.tokenize(prefixToken).map(function (t) {
t.index = 0;
return t;
});
tokens.unshift.apply(tokens, prefixTokens);
}
return new _ParseAST(input, location, tokens, input.length, false, this.errors, 0)
.parseTemplateBindings();
};
/**
* @param {?} input
* @param {?} location
* @param {?=} interpolationConfig
* @return {?}
*/
Parser.prototype.parseInterpolation = function (input, location, interpolationConfig) {
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
var /** @type {?} */ split = this.splitInterpolation(input, location, interpolationConfig);
if (split == null)
return null;
var /** @type {?} */ expressions = [];
for (var /** @type {?} */ i = 0; i < split.expressions.length; ++i) {
var /** @type {?} */ expressionText = split.expressions[i];
var /** @type {?} */ sourceToLex = this._stripComments(expressionText);
var /** @type {?} */ tokens = this._lexer.tokenize(this._stripComments(split.expressions[i]));
var /** @type {?} */ ast = new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, split.offsets[i] + (expressionText.length - sourceToLex.length))
.parseChain();
expressions.push(ast);
}
return new ASTWithSource(new Interpolation(new ParseSpan(0, input == null ? 0 : input.length), split.strings, expressions), input, location, this.errors);
};
/**
* @param {?} input
* @param {?} location
* @param {?=} interpolationConfig
* @return {?}
*/
Parser.prototype.splitInterpolation = function (input, location, interpolationConfig) {
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
var /** @type {?} */ regexp = _createInterpolateRegExp(interpolationConfig);
var /** @type {?} */ parts = input.split(regexp);
if (parts.length <= 1) {
return null;
}
var /** @type {?} */ strings = [];
var /** @type {?} */ expressions = [];
var /** @type {?} */ offsets = [];
var /** @type {?} */ offset = 0;
for (var /** @type {?} */ i = 0; i < parts.length; i++) {
var /** @type {?} */ part = parts[i];
if (i % 2 === 0) {
// fixed string
strings.push(part);
offset += part.length;
}
else if (part.trim().length > 0) {
offset += interpolationConfig.start.length;
expressions.push(part);
offsets.push(offset);
offset += part.length + interpolationConfig.end.length;
}
else {
this._reportError('Blank expressions are not allowed in interpolated strings', input, "at column " + this._findInterpolationErrorColumn(parts, i, interpolationConfig) + " in", location);
expressions.push('$implict');
offsets.push(offset);
}
}
return new SplitInterpolation(strings, expressions, offsets);
};
/**
* @param {?} input
* @param {?} location
* @return {?}
*/
Parser.prototype.wrapLiteralPrimitive = function (input, location) {
return new ASTWithSource(new LiteralPrimitive(new ParseSpan(0, input == null ? 0 : input.length), input), input, location, this.errors);
};
/**
* @param {?} input
* @return {?}
*/
Parser.prototype._stripComments = function (input) {
var /** @type {?} */ i = this._commentStart(input);
return i != null ? input.substring(0, i).trim() : input;
};
/**
* @param {?} input
* @return {?}
*/
Parser.prototype._commentStart = function (input) {
var /** @type {?} */ outerQuote = null;
for (var /** @type {?} */ i = 0; i < input.length - 1; i++) {
var /** @type {?} */ char = input.charCodeAt(i);
var /** @type {?} */ nextChar = input.charCodeAt(i + 1);
if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
return i;
if (outerQuote === char) {
outerQuote = null;
}
else if (outerQuote == null && isQuote(char)) {
outerQuote = char;
}
}
return null;
};
/**
* @param {?} input
* @param {?} location
* @param {?} interpolationConfig
* @return {?}
*/
Parser.prototype._checkNoInterpolation = function (input, location, interpolationConfig) {
var /** @type {?} */ regexp = _createInterpolateRegExp(interpolationConfig);
var /** @type {?} */ parts = input.split(regexp);
if (parts.length > 1) {
this._reportError("Got interpolation (" + interpolationConfig.start + interpolationConfig.end + ") where expression was expected", input, "at column " + this._findInterpolationErrorColumn(parts, 1, interpolationConfig) + " in", location);
}
};
/**
* @param {?} parts
* @param {?} partInErrIdx
* @param {?} interpolationConfig
* @return {?}
*/
Parser.prototype._findInterpolationErrorColumn = function (parts, partInErrIdx, interpolationConfig) {
var /** @type {?} */ errLocation = '';
for (var /** @type {?} */ j = 0; j < partInErrIdx; j++) {
errLocation += j % 2 === 0 ?
parts[j] :
"" + interpolationConfig.start + parts[j] + interpolationConfig.end;
}
return errLocation.length;
};
return Parser;
}());
Parser.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
Parser.ctorParameters = function () { return [
{ type: Lexer, },
]; };
var _ParseAST = (function () {
/**
* @param {?} input
* @param {?} location
* @param {?} tokens
* @param {?} inputLength
* @param {?} parseAction
* @param {?} errors
* @param {?} offset
*/
function _ParseAST(input, location, tokens, inputLength, parseAction, errors, offset) {
this.input = input;
this.location = location;
this.tokens = tokens;
this.inputLength = inputLength;
this.parseAction = parseAction;
this.errors = errors;
this.offset = offset;
this.rparensExpected = 0;
this.rbracketsExpected = 0;
this.rbracesExpected = 0;
this.index = 0;
}
/**
* @param {?} offset
* @return {?}
*/
_ParseAST.prototype.peek = function (offset) {
var /** @type {?} */ i = this.index + offset;
return i < this.tokens.length ? this.tokens[i] : EOF;
};
Object.defineProperty(_ParseAST.prototype, "next", {
/**
* @return {?}
*/
get: function () { return this.peek(0); },
enumerable: true,
configurable: true
});
Object.defineProperty(_ParseAST.prototype, "inputIndex", {
/**
* @return {?}
*/
get: function () {
return (this.index < this.tokens.length) ? this.next.index + this.offset :
this.inputLength + this.offset;
},
enumerable: true,
configurable: true
});
/**
* @param {?} start
* @return {?}
*/
_ParseAST.prototype.span = function (start) { return new ParseSpan(start, this.inputIndex); };
/**
* @return {?}
*/
_ParseAST.prototype.advance = function () { this.index++; };
/**
* @param {?} code
* @return {?}
*/
_ParseAST.prototype.optionalCharacter = function (code) {
if (this.next.isCharacter(code)) {
this.advance();
return true;
}
else {
return false;
}
};
/**
* @return {?}
*/
_ParseAST.prototype.peekKeywordLet = function () { return this.next.isKeywordLet(); };
/**
* @return {?}
*/
_ParseAST.prototype.peekKeywordAs = function () { return this.next.isKeywordAs(); };
/**
* @param {?} code
* @return {?}
*/
_ParseAST.prototype.expectCharacter = function (code) {
if (this.optionalCharacter(code))
return;
this.error("Missing expected " + String.fromCharCode(code));
};
/**
* @param {?} op
* @return {?}
*/
_ParseAST.prototype.optionalOperator = function (op) {
if (this.next.isOperator(op)) {
this.advance();
return true;
}
else {
return false;
}
};
/**
* @param {?} operator
* @return {?}
*/
_ParseAST.prototype.expectOperator = function (operator) {
if (this.optionalOperator(operator))
return;
this.error("Missing expected operator " + operator);
};
/**
* @return {?}
*/
_ParseAST.prototype.expectIdentifierOrKeyword = function () {
var /** @type {?} */ n = this.next;
if (!n.isIdentifier() && !n.isKeyword()) {
this.error("Unexpected token " + n + ", expected identifier or keyword");
return '';
}
this.advance();
return n.toString();
};
/**
* @return {?}
*/
_ParseAST.prototype.expectIdentifierOrKeywordOrString = function () {
var /** @type {?} */ n = this.next;
if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
this.error("Unexpected token " + n + ", expected identifier, keyword, or string");
return '';
}
this.advance();
return n.toString();
};
/**
* @return {?}
*/
_ParseAST.prototype.parseChain = function () {
var /** @type {?} */ exprs = [];
var /** @type {?} */ start = this.inputIndex;
while (this.index < this.tokens.length) {
var /** @type {?} */ expr = this.parsePipe();
exprs.push(expr);
if (this.optionalCharacter($SEMICOLON)) {
if (!this.parseAction) {
this.error('Binding expression cannot contain chained expression');
}
while (this.optionalCharacter($SEMICOLON)) {
} // read all semicolons
}
else if (this.index < this.tokens.length) {
this.error("Unexpected token '" + this.next + "'");
}
}
if (exprs.length == 0)
return new EmptyExpr(this.span(start));
if (exprs.length == 1)
return exprs[0];
return new Chain(this.span(start), exprs);
};
/**
* @return {?}
*/
_ParseAST.prototype.parsePipe = function () {
var /** @type {?} */ result = this.parseExpression();
if (this.optionalOperator('|')) {
if (this.parseAction) {
this.error('Cannot have a pipe in an action expression');
}
do {
var /** @type {?} */ name = ((this.expectIdentifierOrKeyword()));
var /** @type {?} */ args = [];
while (this.optionalCharacter($COLON)) {
args.push(this.parseExpression());
}
result = new BindingPipe(this.span(result.span.start), result, name, args);
} while (this.optionalOperator('|'));
}
return result;
};
/**
* @return {?}
*/
_ParseAST.prototype.parseExpression = function () { return this.parseConditional(); };
/**
* @return {?}
*/
_ParseAST.prototype.parseConditional = function () {
var /** @type {?} */ start = this.inputIndex;
var /** @type {?} */ result = this.parseLogicalOr();
if (this.optionalOperator('?')) {
var /** @type {?} */ yes = this.parsePipe();
var /** @type {?} */ no = void 0;
if (!this.optionalCharacter($COLON)) {
var /** @type {?} */ end = this.inputIndex;
var /** @type {?} */ expression = this.input.substring(start, end);
this.error("Conditional expression " + expression + " requires all 3 expressions");
no = new EmptyExpr(this.span(start));
}
else {
no = this.parsePipe();
}
return new Conditional(this.span(start), result, yes, no);
}
else {
return result;
}
};
/**
* @return {?}
*/
_ParseAST.prototype.parseLogicalOr = function () {
// '||'
var /** @type {?} */ result = this.parseLogicalAnd();
while (this.optionalOperator('||')) {
var /** @type {?} */ right = this.parseLogicalAnd();
result = new Binary(this.span(result.span.start), '||', result, right);
}
return result;
};
/**
* @return {?}
*/
_ParseAST.prototype.parseLogicalAnd = function () {
// '&&'
var /** @type {?} */ result = this.parseEquality();
while (this.optionalOperator('&&')) {
var /** @type {?} */ right = this.parseEquality();
result = new Binary(this.span(result.span.start), '&&', result, right);
}
return result;
};
/**
* @return {?}
*/
_ParseAST.prototype.parseEquality = function () {
// '==','!=','===','!=='
var /** @type {?} */ result = this.parseRelational();
while (this.next.type == TokenType.Operator) {
var /** @type {?} */ operator = this.next.strValue;
switch (operator) {
case '==':
case '===':
case '!=':
case '!==':
this.advance();
var /** @type {?} */ right = this.parseRelational();
result = new Binary(this.span(result.span.start), operator, result, right);
continue;
}
break;
}
return result;
};
/**
* @return {?}
*/
_ParseAST.prototype.parseRelational = function () {
// '<', '>', '<=', '>='
var /** @type {?} */ result = this.parseAdditive();
while (this.next.type == TokenType.Operator) {
var /** @type {?} */ operator = this.next.strValue;
switch (operator) {
case '<':
case '>':
case '<=':
case '>=':
this.advance();
var /** @type {?} */ right = this.parseAdditive();
result = new Binary(this.span(result.span.start), operator, result, right);
continue;
}
break;
}
return result;
};
/**
* @return {?}
*/
_ParseAST.prototype.parseAdditive = function () {
// '+', '-'
var /** @type {?} */ result = this.parseMultiplicative();
while (this.next.type == TokenType.Operator) {
var /** @type {?} */ operator = this.next.strValue;
switch (operator) {
case '+':
case '-':
this.advance();
var /** @type {?} */ right = this.parseMultiplicative();
result = new Binary(this.span(result.span.start), operator, result, right);
continue;
}
break;
}
return result;
};
/**
* @return {?}
*/
_ParseAST.prototype.parseMultiplicative = function () {
// '*', '%', '/'
var /** @type {?} */ result = this.parsePrefix();
while (this.next.type == TokenType.Operator) {
var /** @type {?} */ operator = this.next.strValue;
switch (operator) {
case '*':
case '%':
case '/':
this.advance();
var /** @type {?} */ right = this.parsePrefix();
result = new Binary(this.span(result.span.start), operator, result, right);
continue;
}
break;
}
return result;
};
/**
* @return {?}
*/
_ParseAST.prototype.parsePrefix = function () {
if (this.next.type == TokenType.Operator) {
var /** @type {?} */ start = this.inputIndex;
var /** @type {?} */ operator = this.next.strValue;
var /** @type {?} */ result = void 0;
switch (operator) {
case '+':
this.advance();
return this.parsePrefix();
case '-':
this.advance();
result = this.parsePrefix();
return new Binary(this.span(start), operator, new LiteralPrimitive(new ParseSpan(start, start), 0), result);
case '!':
this.advance();
result = this.parsePrefix();
return new PrefixNot(this.span(start), result);
}
}
return this.parseCallChain();
};
/**
* @return {?}
*/
_ParseAST.prototype.parseCallChain = function () {
var /** @type {?} */ result = this.parsePrimary();
while (true) {
if (this.optionalCharacter($PERIOD)) {
result = this.parseAccessMemberOrMethodCall(result, false);
}
else if (this.optionalOperator('?.')) {
result = this.parseAccessMemberOrMethodCall(result, true);
}
else if (this.optionalCharacter($LBRACKET)) {
this.rbracketsExpected++;
var /** @type {?} */ key = this.parsePipe();
this.rbracketsExpected--;
this.expectCharacter($RBRACKET);
if (this.optionalOperator('=')) {
var /** @type {?} */ value = this.parseConditional();
result = new KeyedWrite(this.span(result.span.start), result, key, value);
}
else {
result = new KeyedRead(this.span(result.span.start), result, key);
}
}
else if (this.optionalCharacter($LPAREN)) {
this.rparensExpected++;
var /** @type {?} */ args = this.parseCallArguments();
this.rparensExpected--;
this.expectCharacter($RPAREN);
result = new FunctionCall(this.span(result.span.start), result, args);
}
else {
return result;
}
}
};
/**
* @return {?}
*/
_ParseAST.prototype.parsePrimary = function () {
var /** @type {?} */ start = this.inputIndex;
if (this.optionalCharacter($LPAREN)) {
this.rparensExpected++;
var /** @type {?} */ result = this.parsePipe();
this.rparensExpected--;
this.expectCharacter($RPAREN);
return result;
}
else if (this.next.isKeywordNull()) {
this.advance();
return new LiteralPrimitive(this.span(start), null);
}
else if (this.next.isKeywordUndefined()) {
this.advance();
return new LiteralPrimitive(this.span(start), void 0);
}
else if (this.next.isKeywordTrue()) {
this.advance();
return new LiteralPrimitive(this.span(start), true);
}
else if (this.next.isKeywordFalse()) {
this.advance();
return new LiteralPrimitive(this.span(start), false);
}
else if (this.next.isKeywordThis()) {
this.advance();
return new ImplicitReceiver(this.span(start));
}
else if (this.optionalCharacter($LBRACKET)) {
this.rbracketsExpected++;
var /** @type {?} */ elements = this.parseExpressionList($RBRACKET);
this.rbracketsExpected--;
this.expectCharacter($RBRACKET);
return new LiteralArray(this.span(start), elements);
}
else if (this.next.isCharacter($LBRACE)) {
return this.parseLiteralMap();
}
else if (this.next.isIdentifier()) {
return this.parseAccessMemberOrMethodCall(new ImplicitReceiver(this.span(start)), false);
}
else if (this.next.isNumber()) {
var /** @type {?} */ value = this.next.toNumber();
this.advance();
return new LiteralPrimitive(this.span(start), value);
}
else if (this.next.isString()) {
var /** @type {?} */ literalValue = this.next.toString();
this.advance();
return new LiteralPrimitive(this.span(start), literalValue);
}
else if (this.index >= this.tokens.length) {
this.error("Unexpected end of expression: " + this.input);
return new EmptyExpr(this.span(start));
}
else {
this.error("Unexpected token " + this.next);
return new EmptyExpr(this.span(start));
}
};
/**
* @param {?} terminator
* @return {?}
*/
_ParseAST.prototype.parseExpressionList = function (terminator) {
var /** @type {?} */ result = [];
if (!this.next.isCharacter(terminator)) {
do {
result.push(this.parsePipe());
} while (this.optionalCharacter($COMMA));
}
return result;
};
/**
* @return {?}
*/
_ParseAST.prototype.parseLiteralMap = function () {
var /** @type {?} */ keys = [];
var /** @type {?} */ values = [];
var /** @type {?} */ start = this.inputIndex;
this.expectCharacter($LBRACE);
if (!this.optionalCharacter($RBRACE)) {
this.rbracesExpected++;
do {
var /** @type {?} */ key = ((this.expectIdentifierOrKeywordOrString()));
keys.push(key);
this.expectCharacter($COLON);
values.push(this.parsePipe());
} while (this.optionalCharacter($COMMA));
this.rbracesExpected--;
this.expectCharacter($RBRACE);
}
return new LiteralMap(this.span(start), keys, values);
};
/**
* @param {?} receiver
* @param {?=} isSafe
* @return {?}
*/
_ParseAST.prototype.parseAccessMemberOrMethodCall = function (receiver, isSafe) {
if (isSafe === void 0) { isSafe = false; }
var /** @type {?} */ start = receiver.span.start;
var /** @type {?} */ id = ((this.expectIdentifierOrKeyword()));
if (this.optionalCharacter($LPAREN)) {
this.rparensExpected++;
var /** @type {?} */ args = this.parseCallArguments();
this.expectCharacter($RPAREN);
this.rparensExpected--;
var /** @type {?} */ span = this.span(start);
return isSafe ? new SafeMethodCall(span, receiver, id, args) :
new MethodCall(span, receiver, id, args);
}
else {
if (isSafe) {
if (this.optionalOperator('=')) {
this.error('The \'?.\' operator cannot be used in the assignment');
return new EmptyExpr(this.span(start));
}
else {
return new SafePropertyRead(this.span(start), receiver, id);
}
}
else {
if (this.optionalOperator('=')) {
if (!this.parseAction) {
this.error('Bindings cannot contain assignments');
return new EmptyExpr(this.span(start));
}
var /** @type {?} */ value = this.parseConditional();
return new PropertyWrite(this.span(start), receiver, id, value);
}
else {
return new PropertyRead(this.span(start), receiver, id);
}
}
}
};
/**
* @return {?}
*/
_ParseAST.prototype.parseCallArguments = function () {
if (this.next.isCharacter($RPAREN))
return [];
var /** @type {?} */ positionals = [];
do {
positionals.push(this.parsePipe());
} while (this.optionalCharacter($COMMA));
return (positionals);
};
/**
* An identifier, a keyword, a string with an optional `-` inbetween.
* @return {?}
*/
_ParseAST.prototype.expectTemplateBindingKey = function () {
var /** @type {?} */ result = '';
var /** @type {?} */ operatorFound = false;
do {
result += this.expectIdentifierOrKeywordOrString();
operatorFound = this.optionalOperator('-');
if (operatorFound) {
result += '-';
}
} while (operatorFound);
return result.toString();
};
/**
* @return {?}
*/
_ParseAST.prototype.parseTemplateBindings = function () {
var /** @type {?} */ bindings = [];
var /** @type {?} */ prefix = ((null));
var /** @type {?} */ warnings = [];
while (this.index < this.tokens.length) {
var /** @type {?} */ start = this.inputIndex;
var /** @type {?} */ keyIsVar = this.peekKeywordLet();
if (keyIsVar) {
this.advance();
}
var /** @type {?} */ rawKey = this.expectTemplateBindingKey();
var /** @type {?} */ key = rawKey;
if (!keyIsVar) {
if (prefix == null) {
prefix = key;
}
else {
key = prefix + key[0].toUpperCase() + key.substring(1);
}
}
this.optionalCharacter($COLON);
var /** @type {?} */ name = ((null));
var /** @type {?} */ expression = ((null));
if (keyIsVar) {
if (this.optionalOperator('=')) {
name = this.expectTemplateBindingKey();
}
else {
name = '\$implicit';
}
}
else if (this.peekKeywordAs()) {
var /** @type {?} */ letStart = this.inputIndex;
this.advance(); // consume `as`
name = rawKey;
key = this.expectTemplateBindingKey(); // read local var name
keyIsVar = true;
}
else if (this.next !== EOF && !this.peekKeywordLet()) {
var /** @type {?} */ start_2 = this.inputIndex;
var /** @type {?} */ ast = this.parsePipe();
var /** @type {?} */ source = this.input.substring(start_2 - this.offset, this.inputIndex - this.offset);
expression = new ASTWithSource(ast, source, this.location, this.errors);
}
bindings.push(new TemplateBinding(this.span(start), key, keyIsVar, name, expression));
if (this.peekKeywordAs() && !keyIsVar) {
var /** @type {?} */ letStart = this.inputIndex;
this.advance(); // consume `as`
var /** @type {?} */ letName = this.expectTemplateBindingKey(); // read local var name
bindings.push(new TemplateBinding(this.span(letStart), letName, true, key, /** @type {?} */ ((null))));
}
if (!this.optionalCharacter($SEMICOLON)) {
this.optionalCharacter($COMMA);
}
}
return new TemplateBindingParseResult(bindings, warnings, this.errors);
};
/**
* @param {?} message
* @param {?=} index
* @return {?}
*/
_ParseAST.prototype.error = function (message, index) {
if (index === void 0) { index = null; }
this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
this.skip();
};
/**
* @param {?=} index
* @return {?}
*/
_ParseAST.prototype.locationText = function (index) {
if (index === void 0) { index = null; }
if (index == null)
index = this.index;
return (index < this.tokens.length) ? "at column " + (this.tokens[index].index + 1) + " in" :
"at the end of the expression";
};
/**
* @return {?}
*/
_ParseAST.prototype.skip = function () {
var /** @type {?} */ n = this.next;
while (this.index < this.tokens.length && !n.isCharacter($SEMICOLON) &&
(this.rparensExpected <= 0 || !n.isCharacter($RPAREN)) &&
(this.rbracesExpected <= 0 || !n.isCharacter($RBRACE)) &&
(this.rbracketsExpected <= 0 || !n.isCharacter($RBRACKET))) {
if (this.next.isError()) {
this.errors.push(new ParserError(/** @type {?} */ ((this.next.toString())), this.input, this.locationText(), this.location));
}
this.advance();
n = this.next;
}
};
return _ParseAST;
}());
var SimpleExpressionChecker = (function () {
function SimpleExpressionChecker() {
this.errors = [];
}
/**
* @param {?} ast
* @return {?}
*/
SimpleExpressionChecker.check = function (ast) {
var /** @type {?} */ s = new SimpleExpressionChecker();
ast.visit(s);
return s.errors;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitImplicitReceiver = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitInterpolation = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitLiteralPrimitive = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitPropertyRead = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitPropertyWrite = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitSafePropertyRead = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitMethodCall = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitSafeMethodCall = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitFunctionCall = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitLiteralArray = function (ast, context) { this.visitAll(ast.expressions); };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitLiteralMap = function (ast, context) { this.visitAll(ast.values); };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitBinary = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitPrefixNot = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitConditional = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitPipe = function (ast, context) { this.errors.push('pipes'); };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitKeyedRead = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitKeyedWrite = function (ast, context) { };
/**
* @param {?} asts
* @return {?}
*/
SimpleExpressionChecker.prototype.visitAll = function (asts) {
var _this = this;
return asts.map(function (node) { return node.visit(_this); });
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitChain = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
SimpleExpressionChecker.prototype.visitQuote = function (ast, context) { };
return SimpleExpressionChecker;
}());
/**
* @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
*/
var ParseLocation = (function () {
/**
* @param {?} file
* @param {?} offset
* @param {?} line
* @param {?} col
*/
function ParseLocation(file, offset, line, col) {
this.file = file;
this.offset = offset;
this.line = line;
this.col = col;
}
/**
* @return {?}
*/
ParseLocation.prototype.toString = function () {
return this.offset != null ? this.file.url + "@" + this.line + ":" + this.col : this.file.url;
};
/**
* @param {?} delta
* @return {?}
*/
ParseLocation.prototype.moveBy = function (delta) {
var /** @type {?} */ source = this.file.content;
var /** @type {?} */ len = source.length;
var /** @type {?} */ offset = this.offset;
var /** @type {?} */ line = this.line;
var /** @type {?} */ col = this.col;
while (offset > 0 && delta < 0) {
offset--;
delta++;
var /** @type {?} */ ch = source.charCodeAt(offset);
if (ch == $LF) {
line--;
var /** @type {?} */ priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
col = priorLine > 0 ? offset - priorLine : offset;
}
else {
col--;
}
}
while (offset < len && delta > 0) {
var /** @type {?} */ ch = source.charCodeAt(offset);
offset++;
delta--;
if (ch == $LF) {
line++;
col = 0;
}
else {
col++;
}
}
return new ParseLocation(this.file, offset, line, col);
};
/**
* @param {?} maxChars
* @param {?} maxLines
* @return {?}
*/
ParseLocation.prototype.getContext = function (maxChars, maxLines) {
var /** @type {?} */ content = this.file.content;
var /** @type {?} */ startOffset = this.offset;
if (startOffset != null) {
if (startOffset > content.length - 1) {
startOffset = content.length - 1;
}
var /** @type {?} */ endOffset = startOffset;
var /** @type {?} */ ctxChars = 0;
var /** @type {?} */ ctxLines = 0;
while (ctxChars < maxChars && startOffset > 0) {
startOffset--;
ctxChars++;
if (content[startOffset] == '\n') {
if (++ctxLines == maxLines) {
break;
}
}
}
ctxChars = 0;
ctxLines = 0;
while (ctxChars < maxChars && endOffset < content.length - 1) {
endOffset++;
ctxChars++;
if (content[endOffset] == '\n') {
if (++ctxLines == maxLines) {
break;
}
}
}
return {
before: content.substring(startOffset, this.offset),
after: content.substring(this.offset, endOffset + 1),
};
}
return null;
};
return ParseLocation;
}());
var ParseSourceFile = (function () {
/**
* @param {?} content
* @param {?} url
*/
function ParseSourceFile(content, url) {
this.content = content;
this.url = url;
}
return ParseSourceFile;
}());
var ParseSourceSpan = (function () {
/**
* @param {?} start
* @param {?} end
* @param {?=} details
*/
function ParseSourceSpan(start, end, details) {
if (details === void 0) { details = null; }
this.start = start;
this.end = end;
this.details = details;
}
/**
* @return {?}
*/
ParseSourceSpan.prototype.toString = function () {
return this.start.file.content.substring(this.start.offset, this.end.offset);
};
return ParseSourceSpan;
}());
var ParseErrorLevel = {};
ParseErrorLevel.WARNING = 0;
ParseErrorLevel.ERROR = 1;
ParseErrorLevel[ParseErrorLevel.WARNING] = "WARNING";
ParseErrorLevel[ParseErrorLevel.ERROR] = "ERROR";
var ParseError = (function () {
/**
* @param {?} span
* @param {?} msg
* @param {?=} level
*/
function ParseError(span, msg, level) {
if (level === void 0) { level = ParseErrorLevel.ERROR; }
this.span = span;
this.msg = msg;
this.level = level;
}
/**
* @return {?}
*/
ParseError.prototype.toString = function () {
var /** @type {?} */ ctx = this.span.start.getContext(100, 3);
var /** @type {?} */ contextStr = ctx ? " (\"" + ctx.before + "[" + ParseErrorLevel[this.level] + " ->]" + ctx.after + "\")" : '';
var /** @type {?} */ details = this.span.details ? ", " + this.span.details : '';
return "" + this.msg + contextStr + ": " + this.span.start + details;
};
return ParseError;
}());
/**
* @param {?} kind
* @param {?} type
* @return {?}
*/
function typeSourceSpan(kind, type) {
var /** @type {?} */ moduleUrl = identifierModuleUrl(type);
var /** @type {?} */ sourceFileName = moduleUrl != null ? "in " + kind + " " + identifierName(type) + " in " + moduleUrl :
"in " + kind + " " + identifierName(type);
var /** @type {?} */ sourceFile = new ParseSourceFile('', sourceFileName);
return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
}
/**
* @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
*/
var Text = (function () {
/**
* @param {?} value
* @param {?} sourceSpan
*/
function Text(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
return Text;
}());
var Expansion = (function () {
/**
* @param {?} switchValue
* @param {?} type
* @param {?} cases
* @param {?} sourceSpan
* @param {?} switchValueSourceSpan
*/
function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan) {
this.switchValue = switchValue;
this.type = type;
this.cases = cases;
this.sourceSpan = sourceSpan;
this.switchValueSourceSpan = switchValueSourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
Expansion.prototype.visit = function (visitor, context) { return visitor.visitExpansion(this, context); };
return Expansion;
}());
var ExpansionCase = (function () {
/**
* @param {?} value
* @param {?} expression
* @param {?} sourceSpan
* @param {?} valueSourceSpan
* @param {?} expSourceSpan
*/
function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
this.value = value;
this.expression = expression;
this.sourceSpan = sourceSpan;
this.valueSourceSpan = valueSourceSpan;
this.expSourceSpan = expSourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); };
return ExpansionCase;
}());
var Attribute$1 = (function () {
/**
* @param {?} name
* @param {?} value
* @param {?} sourceSpan
* @param {?=} valueSpan
*/
function Attribute$1(name, value, sourceSpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.valueSpan = valueSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
Attribute$1.prototype.visit = function (visitor, context) { return visitor.visitAttribute(this, context); };
return Attribute$1;
}());
var Element = (function () {
/**
* @param {?} name
* @param {?} attrs
* @param {?} children
* @param {?} sourceSpan
* @param {?=} startSourceSpan
* @param {?=} endSourceSpan
*/
function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan) {
if (startSourceSpan === void 0) { startSourceSpan = null; }
if (endSourceSpan === void 0) { endSourceSpan = null; }
this.name = name;
this.attrs = attrs;
this.children = children;
this.sourceSpan = sourceSpan;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
Element.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); };
return Element;
}());
var Comment = (function () {
/**
* @param {?} value
* @param {?} sourceSpan
*/
function Comment(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
Comment.prototype.visit = function (visitor, context) { return visitor.visitComment(this, context); };
return Comment;
}());
/**
* @param {?} visitor
* @param {?} nodes
* @param {?=} context
* @return {?}
*/
function visitAll(visitor, nodes, context) {
if (context === void 0) { context = null; }
var /** @type {?} */ result = [];
var /** @type {?} */ visit = visitor.visit ?
function (ast) { return ((visitor.visit))(ast, context) || ast.visit(visitor, context); } :
function (ast) { return ast.visit(visitor, context); };
nodes.forEach(function (ast) {
var /** @type {?} */ astResult = visit(ast);
if (astResult) {
result.push(astResult);
}
});
return result;
}
/**
* @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
*/
var TokenType$1 = {};
TokenType$1.TAG_OPEN_START = 0;
TokenType$1.TAG_OPEN_END = 1;
TokenType$1.TAG_OPEN_END_VOID = 2;
TokenType$1.TAG_CLOSE = 3;
TokenType$1.TEXT = 4;
TokenType$1.ESCAPABLE_RAW_TEXT = 5;
TokenType$1.RAW_TEXT = 6;
TokenType$1.COMMENT_START = 7;
TokenType$1.COMMENT_END = 8;
TokenType$1.CDATA_START = 9;
TokenType$1.CDATA_END = 10;
TokenType$1.ATTR_NAME = 11;
TokenType$1.ATTR_VALUE = 12;
TokenType$1.DOC_TYPE = 13;
TokenType$1.EXPANSION_FORM_START = 14;
TokenType$1.EXPANSION_CASE_VALUE = 15;
TokenType$1.EXPANSION_CASE_EXP_START = 16;
TokenType$1.EXPANSION_CASE_EXP_END = 17;
TokenType$1.EXPANSION_FORM_END = 18;
TokenType$1.EOF = 19;
TokenType$1[TokenType$1.TAG_OPEN_START] = "TAG_OPEN_START";
TokenType$1[TokenType$1.TAG_OPEN_END] = "TAG_OPEN_END";
TokenType$1[TokenType$1.TAG_OPEN_END_VOID] = "TAG_OPEN_END_VOID";
TokenType$1[TokenType$1.TAG_CLOSE] = "TAG_CLOSE";
TokenType$1[TokenType$1.TEXT] = "TEXT";
TokenType$1[TokenType$1.ESCAPABLE_RAW_TEXT] = "ESCAPABLE_RAW_TEXT";
TokenType$1[TokenType$1.RAW_TEXT] = "RAW_TEXT";
TokenType$1[TokenType$1.COMMENT_START] = "COMMENT_START";
TokenType$1[TokenType$1.COMMENT_END] = "COMMENT_END";
TokenType$1[TokenType$1.CDATA_START] = "CDATA_START";
TokenType$1[TokenType$1.CDATA_END] = "CDATA_END";
TokenType$1[TokenType$1.ATTR_NAME] = "ATTR_NAME";
TokenType$1[TokenType$1.ATTR_VALUE] = "ATTR_VALUE";
TokenType$1[TokenType$1.DOC_TYPE] = "DOC_TYPE";
TokenType$1[TokenType$1.EXPANSION_FORM_START] = "EXPANSION_FORM_START";
TokenType$1[TokenType$1.EXPANSION_CASE_VALUE] = "EXPANSION_CASE_VALUE";
TokenType$1[TokenType$1.EXPANSION_CASE_EXP_START] = "EXPANSION_CASE_EXP_START";
TokenType$1[TokenType$1.EXPANSION_CASE_EXP_END] = "EXPANSION_CASE_EXP_END";
TokenType$1[TokenType$1.EXPANSION_FORM_END] = "EXPANSION_FORM_END";
TokenType$1[TokenType$1.EOF] = "EOF";
var Token$1 = (function () {
/**
* @param {?} type
* @param {?} parts
* @param {?} sourceSpan
*/
function Token$1(type, parts, sourceSpan) {
this.type = type;
this.parts = parts;
this.sourceSpan = sourceSpan;
}
return Token$1;
}());
var TokenError = (function (_super) {
__extends(TokenError, _super);
/**
* @param {?} errorMsg
* @param {?} tokenType
* @param {?} span
*/
function TokenError(errorMsg, tokenType, span) {
var _this = _super.call(this, span, errorMsg) || this;
_this.tokenType = tokenType;
return _this;
}
return TokenError;
}(ParseError));
var TokenizeResult = (function () {
/**
* @param {?} tokens
* @param {?} errors
*/
function TokenizeResult(tokens, errors) {
this.tokens = tokens;
this.errors = errors;
}
return TokenizeResult;
}());
/**
* @param {?} source
* @param {?} url
* @param {?} getTagDefinition
* @param {?=} tokenizeExpansionForms
* @param {?=} interpolationConfig
* @return {?}
*/
function tokenize(source, url, getTagDefinition, tokenizeExpansionForms, interpolationConfig) {
if (tokenizeExpansionForms === void 0) { tokenizeExpansionForms = false; }
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
return new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, tokenizeExpansionForms, interpolationConfig)
.tokenize();
}
var _CR_OR_CRLF_REGEXP = /\r\n?/g;
/**
* @param {?} charCode
* @return {?}
*/
function _unexpectedCharacterErrorMsg(charCode) {
var /** @type {?} */ char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode);
return "Unexpected character \"" + char + "\"";
}
/**
* @param {?} entitySrc
* @return {?}
*/
function _unknownEntityErrorMsg(entitySrc) {
return "Unknown entity \"" + entitySrc + "\" - use the \"&#<decimal>;\" or \"&#x<hex>;\" syntax";
}
var _ControlFlowError = (function () {
/**
* @param {?} error
*/
function _ControlFlowError(error) {
this.error = error;
}
return _ControlFlowError;
}());
var _Tokenizer = (function () {
/**
* @param {?} _file The html source
* @param {?} _getTagDefinition
* @param {?} _tokenizeIcu Whether to tokenize ICU messages (considered as text nodes when false)
* @param {?=} _interpolationConfig
*/
function _Tokenizer(_file, _getTagDefinition, _tokenizeIcu, _interpolationConfig) {
if (_interpolationConfig === void 0) { _interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
this._file = _file;
this._getTagDefinition = _getTagDefinition;
this._tokenizeIcu = _tokenizeIcu;
this._interpolationConfig = _interpolationConfig;
this._peek = -1;
this._nextPeek = -1;
this._index = -1;
this._line = 0;
this._column = -1;
this._expansionCaseStack = [];
this._inInterpolation = false;
this.tokens = [];
this.errors = [];
this._input = _file.content;
this._length = _file.content.length;
this._advance();
}
/**
* @param {?} content
* @return {?}
*/
_Tokenizer.prototype._processCarriageReturns = function (content) {
// http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream
// In order to keep the original position in the source, we can not
// pre-process it.
// Instead CRs are processed right before instantiating the tokens.
return content.replace(_CR_OR_CRLF_REGEXP, '\n');
};
/**
* @return {?}
*/
_Tokenizer.prototype.tokenize = function () {
while (this._peek !== $EOF) {
var /** @type {?} */ start = this._getLocation();
try {
if (this._attemptCharCode($LT)) {
if (this._attemptCharCode($BANG)) {
if (this._attemptCharCode($LBRACKET)) {
this._consumeCdata(start);
}
else if (this._attemptCharCode($MINUS)) {
this._consumeComment(start);
}
else {
this._consumeDocType(start);
}
}
else if (this._attemptCharCode($SLASH)) {
this._consumeTagClose(start);
}
else {
this._consumeTagOpen(start);
}
}
else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
this._consumeText();
}
}
catch (e) {
if (e instanceof _ControlFlowError) {
this.errors.push(e.error);
}
else {
throw e;
}
}
}
this._beginToken(TokenType$1.EOF);
this._endToken([]);
return new TokenizeResult(mergeTextTokens(this.tokens), this.errors);
};
/**
* \@internal
* @return {?}
*/
_Tokenizer.prototype._tokenizeExpansionForm = function () {
if (isExpansionFormStart(this._input, this._index, this._interpolationConfig)) {
this._consumeExpansionFormStart();
return true;
}
if (isExpansionCaseStart(this._peek) && this._isInExpansionForm()) {
this._consumeExpansionCaseStart();
return true;
}
if (this._peek === $RBRACE) {
if (this._isInExpansionCase()) {
this._consumeExpansionCaseEnd();
return true;
}
if (this._isInExpansionForm()) {
this._consumeExpansionFormEnd();
return true;
}
}
return false;
};
/**
* @return {?}
*/
_Tokenizer.prototype._getLocation = function () {
return new ParseLocation(this._file, this._index, this._line, this._column);
};
/**
* @param {?=} start
* @param {?=} end
* @return {?}
*/
_Tokenizer.prototype._getSpan = function (start, end) {
if (start === void 0) { start = this._getLocation(); }
if (end === void 0) { end = this._getLocation(); }
return new ParseSourceSpan(start, end);
};
/**
* @param {?} type
* @param {?=} start
* @return {?}
*/
_Tokenizer.prototype._beginToken = function (type, start) {
if (start === void 0) { start = this._getLocation(); }
this._currentTokenStart = start;
this._currentTokenType = type;
};
/**
* @param {?} parts
* @param {?=} end
* @return {?}
*/
_Tokenizer.prototype._endToken = function (parts, end) {
if (end === void 0) { end = this._getLocation(); }
var /** @type {?} */ token = new Token$1(this._currentTokenType, parts, new ParseSourceSpan(this._currentTokenStart, end));
this.tokens.push(token);
this._currentTokenStart = ((null));
this._currentTokenType = ((null));
return token;
};
/**
* @param {?} msg
* @param {?} span
* @return {?}
*/
_Tokenizer.prototype._createError = function (msg, span) {
if (this._isInExpansionForm()) {
msg += " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)";
}
var /** @type {?} */ error = new TokenError(msg, this._currentTokenType, span);
this._currentTokenStart = ((null));
this._currentTokenType = ((null));
return new _ControlFlowError(error);
};
/**
* @return {?}
*/
_Tokenizer.prototype._advance = function () {
if (this._index >= this._length) {
throw this._createError(_unexpectedCharacterErrorMsg($EOF), this._getSpan());
}
if (this._peek === $LF) {
this._line++;
this._column = 0;
}
else if (this._peek !== $LF && this._peek !== $CR) {
this._column++;
}
this._index++;
this._peek = this._index >= this._length ? $EOF : this._input.charCodeAt(this._index);
this._nextPeek =
this._index + 1 >= this._length ? $EOF : this._input.charCodeAt(this._index + 1);
};
/**
* @param {?} charCode
* @return {?}
*/
_Tokenizer.prototype._attemptCharCode = function (charCode) {
if (this._peek === charCode) {
this._advance();
return true;
}
return false;
};
/**
* @param {?} charCode
* @return {?}
*/
_Tokenizer.prototype._attemptCharCodeCaseInsensitive = function (charCode) {
if (compareCharCodeCaseInsensitive(this._peek, charCode)) {
this._advance();
return true;
}
return false;
};
/**
* @param {?} charCode
* @return {?}
*/
_Tokenizer.prototype._requireCharCode = function (charCode) {
var /** @type {?} */ location = this._getLocation();
if (!this._attemptCharCode(charCode)) {
throw this._createError(_unexpectedCharacterErrorMsg(this._peek), this._getSpan(location, location));
}
};
/**
* @param {?} chars
* @return {?}
*/
_Tokenizer.prototype._attemptStr = function (chars) {
var /** @type {?} */ len = chars.length;
if (this._index + len > this._length) {
return false;
}
var /** @type {?} */ initialPosition = this._savePosition();
for (var /** @type {?} */ i = 0; i < len; i++) {
if (!this._attemptCharCode(chars.charCodeAt(i))) {
// If attempting to parse the string fails, we want to reset the parser
// to where it was before the attempt
this._restorePosition(initialPosition);
return false;
}
}
return true;
};
/**
* @param {?} chars
* @return {?}
*/
_Tokenizer.prototype._attemptStrCaseInsensitive = function (chars) {
for (var /** @type {?} */ i = 0; i < chars.length; i++) {
if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
return false;
}
}
return true;
};
/**
* @param {?} chars
* @return {?}
*/
_Tokenizer.prototype._requireStr = function (chars) {
var /** @type {?} */ location = this._getLocation();
if (!this._attemptStr(chars)) {
throw this._createError(_unexpectedCharacterErrorMsg(this._peek), this._getSpan(location));
}
};
/**
* @param {?} predicate
* @return {?}
*/
_Tokenizer.prototype._attemptCharCodeUntilFn = function (predicate) {
while (!predicate(this._peek)) {
this._advance();
}
};
/**
* @param {?} predicate
* @param {?} len
* @return {?}
*/
_Tokenizer.prototype._requireCharCodeUntilFn = function (predicate, len) {
var /** @type {?} */ start = this._getLocation();
this._attemptCharCodeUntilFn(predicate);
if (this._index - start.offset < len) {
throw this._createError(_unexpectedCharacterErrorMsg(this._peek), this._getSpan(start, start));
}
};
/**
* @param {?} char
* @return {?}
*/
_Tokenizer.prototype._attemptUntilChar = function (char) {
while (this._peek !== char) {
this._advance();
}
};
/**
* @param {?} decodeEntities
* @return {?}
*/
_Tokenizer.prototype._readChar = function (decodeEntities) {
if (decodeEntities && this._peek === $AMPERSAND) {
return this._decodeEntity();
}
else {
var /** @type {?} */ index = this._index;
this._advance();
return this._input[index];
}
};
/**
* @return {?}
*/
_Tokenizer.prototype._decodeEntity = function () {
var /** @type {?} */ start = this._getLocation();
this._advance();
if (this._attemptCharCode($HASH)) {
var /** @type {?} */ isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
var /** @type {?} */ numberStart = this._getLocation().offset;
this._attemptCharCodeUntilFn(isDigitEntityEnd);
if (this._peek != $SEMICOLON) {
throw this._createError(_unexpectedCharacterErrorMsg(this._peek), this._getSpan());
}
this._advance();
var /** @type {?} */ strNum = this._input.substring(numberStart, this._index - 1);
try {
var /** @type {?} */ charCode = parseInt(strNum, isHex ? 16 : 10);
return String.fromCharCode(charCode);
}
catch (e) {
var /** @type {?} */ entity = this._input.substring(start.offset + 1, this._index - 1);
throw this._createError(_unknownEntityErrorMsg(entity), this._getSpan(start));
}
}
else {
var /** @type {?} */ startPosition = this._savePosition();
this._attemptCharCodeUntilFn(isNamedEntityEnd);
if (this._peek != $SEMICOLON) {
this._restorePosition(startPosition);
return '&';
}
this._advance();
var /** @type {?} */ name = this._input.substring(start.offset + 1, this._index - 1);
var /** @type {?} */ char = NAMED_ENTITIES[name];
if (!char) {
throw this._createError(_unknownEntityErrorMsg(name), this._getSpan(start));
}
return char;
}
};
/**
* @param {?} decodeEntities
* @param {?} firstCharOfEnd
* @param {?} attemptEndRest
* @return {?}
*/
_Tokenizer.prototype._consumeRawText = function (decodeEntities, firstCharOfEnd, attemptEndRest) {
var /** @type {?} */ tagCloseStart;
var /** @type {?} */ textStart = this._getLocation();
this._beginToken(decodeEntities ? TokenType$1.ESCAPABLE_RAW_TEXT : TokenType$1.RAW_TEXT, textStart);
var /** @type {?} */ parts = [];
while (true) {
tagCloseStart = this._getLocation();
if (this._attemptCharCode(firstCharOfEnd) && attemptEndRest()) {
break;
}
if (this._index > tagCloseStart.offset) {
// add the characters consumed by the previous if statement to the output
parts.push(this._input.substring(tagCloseStart.offset, this._index));
}
while (this._peek !== firstCharOfEnd) {
parts.push(this._readChar(decodeEntities));
}
}
return this._endToken([this._processCarriageReturns(parts.join(''))], tagCloseStart);
};
/**
* @param {?} start
* @return {?}
*/
_Tokenizer.prototype._consumeComment = function (start) {
var _this = this;
this._beginToken(TokenType$1.COMMENT_START, start);
this._requireCharCode($MINUS);
this._endToken([]);
var /** @type {?} */ textToken = this._consumeRawText(false, $MINUS, function () { return _this._attemptStr('->'); });
this._beginToken(TokenType$1.COMMENT_END, textToken.sourceSpan.end);
this._endToken([]);
};
/**
* @param {?} start
* @return {?}
*/
_Tokenizer.prototype._consumeCdata = function (start) {
var _this = this;
this._beginToken(TokenType$1.CDATA_START, start);
this._requireStr('CDATA[');
this._endToken([]);
var /** @type {?} */ textToken = this._consumeRawText(false, $RBRACKET, function () { return _this._attemptStr(']>'); });
this._beginToken(TokenType$1.CDATA_END, textToken.sourceSpan.end);
this._endToken([]);
};
/**
* @param {?} start
* @return {?}
*/
_Tokenizer.prototype._consumeDocType = function (start) {
this._beginToken(TokenType$1.DOC_TYPE, start);
this._attemptUntilChar($GT);
this._advance();
this._endToken([this._input.substring(start.offset + 2, this._index - 1)]);
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumePrefixAndName = function () {
var /** @type {?} */ nameOrPrefixStart = this._index;
var /** @type {?} */ prefix = ((null));
while (this._peek !== $COLON && !isPrefixEnd(this._peek)) {
this._advance();
}
var /** @type {?} */ nameStart;
if (this._peek === $COLON) {
this._advance();
prefix = this._input.substring(nameOrPrefixStart, this._index - 1);
nameStart = this._index;
}
else {
nameStart = nameOrPrefixStart;
}
this._requireCharCodeUntilFn(isNameEnd, this._index === nameStart ? 1 : 0);
var /** @type {?} */ name = this._input.substring(nameStart, this._index);
return [prefix, name];
};
/**
* @param {?} start
* @return {?}
*/
_Tokenizer.prototype._consumeTagOpen = function (start) {
var /** @type {?} */ savedPos = this._savePosition();
var /** @type {?} */ tagName;
var /** @type {?} */ lowercaseTagName;
try {
if (!isAsciiLetter(this._peek)) {
throw this._createError(_unexpectedCharacterErrorMsg(this._peek), this._getSpan());
}
var /** @type {?} */ nameStart = this._index;
this._consumeTagOpenStart(start);
tagName = this._input.substring(nameStart, this._index);
lowercaseTagName = tagName.toLowerCase();
this._attemptCharCodeUntilFn(isNotWhitespace);
while (this._peek !== $SLASH && this._peek !== $GT) {
this._consumeAttributeName();
this._attemptCharCodeUntilFn(isNotWhitespace);
if (this._attemptCharCode($EQ)) {
this._attemptCharCodeUntilFn(isNotWhitespace);
this._consumeAttributeValue();
}
this._attemptCharCodeUntilFn(isNotWhitespace);
}
this._consumeTagOpenEnd();
}
catch (e) {
if (e instanceof _ControlFlowError) {
// When the start tag is invalid, assume we want a "<"
this._restorePosition(savedPos);
// Back to back text tokens are merged at the end
this._beginToken(TokenType$1.TEXT, start);
this._endToken(['<']);
return;
}
throw e;
}
var /** @type {?} */ contentTokenType = this._getTagDefinition(tagName).contentType;
if (contentTokenType === TagContentType.RAW_TEXT) {
this._consumeRawTextWithTagClose(lowercaseTagName, false);
}
else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) {
this._consumeRawTextWithTagClose(lowercaseTagName, true);
}
};
/**
* @param {?} lowercaseTagName
* @param {?} decodeEntities
* @return {?}
*/
_Tokenizer.prototype._consumeRawTextWithTagClose = function (lowercaseTagName, decodeEntities) {
var _this = this;
var /** @type {?} */ textToken = this._consumeRawText(decodeEntities, $LT, function () {
if (!_this._attemptCharCode($SLASH))
return false;
_this._attemptCharCodeUntilFn(isNotWhitespace);
if (!_this._attemptStrCaseInsensitive(lowercaseTagName))
return false;
_this._attemptCharCodeUntilFn(isNotWhitespace);
return _this._attemptCharCode($GT);
});
this._beginToken(TokenType$1.TAG_CLOSE, textToken.sourceSpan.end);
this._endToken([/** @type {?} */ ((null)), lowercaseTagName]);
};
/**
* @param {?} start
* @return {?}
*/
_Tokenizer.prototype._consumeTagOpenStart = function (start) {
this._beginToken(TokenType$1.TAG_OPEN_START, start);
var /** @type {?} */ parts = this._consumePrefixAndName();
this._endToken(parts);
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumeAttributeName = function () {
this._beginToken(TokenType$1.ATTR_NAME);
var /** @type {?} */ prefixAndName = this._consumePrefixAndName();
this._endToken(prefixAndName);
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumeAttributeValue = function () {
this._beginToken(TokenType$1.ATTR_VALUE);
var /** @type {?} */ value;
if (this._peek === $SQ || this._peek === $DQ) {
var /** @type {?} */ quoteChar = this._peek;
this._advance();
var /** @type {?} */ parts = [];
while (this._peek !== quoteChar) {
parts.push(this._readChar(true));
}
value = parts.join('');
this._advance();
}
else {
var /** @type {?} */ valueStart = this._index;
this._requireCharCodeUntilFn(isNameEnd, 1);
value = this._input.substring(valueStart, this._index);
}
this._endToken([this._processCarriageReturns(value)]);
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumeTagOpenEnd = function () {
var /** @type {?} */ tokenType = this._attemptCharCode($SLASH) ? TokenType$1.TAG_OPEN_END_VOID : TokenType$1.TAG_OPEN_END;
this._beginToken(tokenType);
this._requireCharCode($GT);
this._endToken([]);
};
/**
* @param {?} start
* @return {?}
*/
_Tokenizer.prototype._consumeTagClose = function (start) {
this._beginToken(TokenType$1.TAG_CLOSE, start);
this._attemptCharCodeUntilFn(isNotWhitespace);
var /** @type {?} */ prefixAndName = this._consumePrefixAndName();
this._attemptCharCodeUntilFn(isNotWhitespace);
this._requireCharCode($GT);
this._endToken(prefixAndName);
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumeExpansionFormStart = function () {
this._beginToken(TokenType$1.EXPANSION_FORM_START, this._getLocation());
this._requireCharCode($LBRACE);
this._endToken([]);
this._expansionCaseStack.push(TokenType$1.EXPANSION_FORM_START);
this._beginToken(TokenType$1.RAW_TEXT, this._getLocation());
var /** @type {?} */ condition = this._readUntil($COMMA);
this._endToken([condition], this._getLocation());
this._requireCharCode($COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(TokenType$1.RAW_TEXT, this._getLocation());
var /** @type {?} */ type = this._readUntil($COMMA);
this._endToken([type], this._getLocation());
this._requireCharCode($COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace);
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumeExpansionCaseStart = function () {
this._beginToken(TokenType$1.EXPANSION_CASE_VALUE, this._getLocation());
var /** @type {?} */ value = this._readUntil($LBRACE).trim();
this._endToken([value], this._getLocation());
this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(TokenType$1.EXPANSION_CASE_EXP_START, this._getLocation());
this._requireCharCode($LBRACE);
this._endToken([], this._getLocation());
this._attemptCharCodeUntilFn(isNotWhitespace);
this._expansionCaseStack.push(TokenType$1.EXPANSION_CASE_EXP_START);
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumeExpansionCaseEnd = function () {
this._beginToken(TokenType$1.EXPANSION_CASE_EXP_END, this._getLocation());
this._requireCharCode($RBRACE);
this._endToken([], this._getLocation());
this._attemptCharCodeUntilFn(isNotWhitespace);
this._expansionCaseStack.pop();
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumeExpansionFormEnd = function () {
this._beginToken(TokenType$1.EXPANSION_FORM_END, this._getLocation());
this._requireCharCode($RBRACE);
this._endToken([]);
this._expansionCaseStack.pop();
};
/**
* @return {?}
*/
_Tokenizer.prototype._consumeText = function () {
var /** @type {?} */ start = this._getLocation();
this._beginToken(TokenType$1.TEXT, start);
var /** @type {?} */ parts = [];
do {
if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
parts.push(this._interpolationConfig.start);
this._inInterpolation = true;
}
else if (this._interpolationConfig && this._inInterpolation &&
this._attemptStr(this._interpolationConfig.end)) {
parts.push(this._interpolationConfig.end);
this._inInterpolation = false;
}
else {
parts.push(this._readChar(true));
}
} while (!this._isTextEnd());
this._endToken([this._processCarriageReturns(parts.join(''))]);
};
/**
* @return {?}
*/
_Tokenizer.prototype._isTextEnd = function () {
if (this._peek === $LT || this._peek === $EOF) {
return true;
}
if (this._tokenizeIcu && !this._inInterpolation) {
if (isExpansionFormStart(this._input, this._index, this._interpolationConfig)) {
// start of an expansion form
return true;
}
if (this._peek === $RBRACE && this._isInExpansionCase()) {
// end of and expansion case
return true;
}
}
return false;
};
/**
* @return {?}
*/
_Tokenizer.prototype._savePosition = function () {
return [this._peek, this._index, this._column, this._line, this.tokens.length];
};
/**
* @param {?} char
* @return {?}
*/
_Tokenizer.prototype._readUntil = function (char) {
var /** @type {?} */ start = this._index;
this._attemptUntilChar(char);
return this._input.substring(start, this._index);
};
/**
* @param {?} position
* @return {?}
*/
_Tokenizer.prototype._restorePosition = function (position) {
this._peek = position[0];
this._index = position[1];
this._column = position[2];
this._line = position[3];
var /** @type {?} */ nbTokens = position[4];
if (nbTokens < this.tokens.length) {
// remove any extra tokens
this.tokens = this.tokens.slice(0, nbTokens);
}
};
/**
* @return {?}
*/
_Tokenizer.prototype._isInExpansionCase = function () {
return this._expansionCaseStack.length > 0 &&
this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
TokenType$1.EXPANSION_CASE_EXP_START;
};
/**
* @return {?}
*/
_Tokenizer.prototype._isInExpansionForm = function () {
return this._expansionCaseStack.length > 0 &&
this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
TokenType$1.EXPANSION_FORM_START;
};
return _Tokenizer;
}());
/**
* @param {?} code
* @return {?}
*/
function isNotWhitespace(code) {
return !isWhitespace(code) || code === $EOF;
}
/**
* @param {?} code
* @return {?}
*/
function isNameEnd(code) {
return isWhitespace(code) || code === $GT || code === $SLASH ||
code === $SQ || code === $DQ || code === $EQ;
}
/**
* @param {?} code
* @return {?}
*/
function isPrefixEnd(code) {
return (code < $a || $z < code) && (code < $A || $Z < code) &&
(code < $0 || code > $9);
}
/**
* @param {?} code
* @return {?}
*/
function isDigitEntityEnd(code) {
return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
}
/**
* @param {?} code
* @return {?}
*/
function isNamedEntityEnd(code) {
return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
}
/**
* @param {?} input
* @param {?} offset
* @param {?} interpolationConfig
* @return {?}
*/
function isExpansionFormStart(input, offset, interpolationConfig) {
var /** @type {?} */ isInterpolationStart = interpolationConfig ? input.indexOf(interpolationConfig.start, offset) == offset : false;
return input.charCodeAt(offset) == $LBRACE && !isInterpolationStart;
}
/**
* @param {?} peek
* @return {?}
*/
function isExpansionCaseStart(peek) {
return peek === $EQ || isAsciiLetter(peek);
}
/**
* @param {?} code1
* @param {?} code2
* @return {?}
*/
function compareCharCodeCaseInsensitive(code1, code2) {
return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2);
}
/**
* @param {?} code
* @return {?}
*/
function toUpperCaseCharCode(code) {
return code >= $a && code <= $z ? code - $a + $A : code;
}
/**
* @param {?} srcTokens
* @return {?}
*/
function mergeTextTokens(srcTokens) {
var /** @type {?} */ dstTokens = [];
var /** @type {?} */ lastDstToken = undefined;
for (var /** @type {?} */ i = 0; i < srcTokens.length; i++) {
var /** @type {?} */ token = srcTokens[i];
if (lastDstToken && lastDstToken.type == TokenType$1.TEXT && token.type == TokenType$1.TEXT) {
lastDstToken.parts[0] += token.parts[0];
lastDstToken.sourceSpan.end = token.sourceSpan.end;
}
else {
lastDstToken = token;
dstTokens.push(lastDstToken);
}
}
return dstTokens;
}
/**
* @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
*/
var TreeError = (function (_super) {
__extends(TreeError, _super);
/**
* @param {?} elementName
* @param {?} span
* @param {?} msg
*/
function TreeError(elementName, span, msg) {
var _this = _super.call(this, span, msg) || this;
_this.elementName = elementName;
return _this;
}
/**
* @param {?} elementName
* @param {?} span
* @param {?} msg
* @return {?}
*/
TreeError.create = function (elementName, span, msg) {
return new TreeError(elementName, span, msg);
};
return TreeError;
}(ParseError));
var ParseTreeResult = (function () {
/**
* @param {?} rootNodes
* @param {?} errors
*/
function ParseTreeResult(rootNodes, errors) {
this.rootNodes = rootNodes;
this.errors = errors;
}
return ParseTreeResult;
}());
var Parser$1 = (function () {
/**
* @param {?} getTagDefinition
*/
function Parser$1(getTagDefinition) {
this.getTagDefinition = getTagDefinition;
}
/**
* @param {?} source
* @param {?} url
* @param {?=} parseExpansionForms
* @param {?=} interpolationConfig
* @return {?}
*/
Parser$1.prototype.parse = function (source, url, parseExpansionForms, interpolationConfig) {
if (parseExpansionForms === void 0) { parseExpansionForms = false; }
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
var /** @type {?} */ tokensAndErrors = tokenize(source, url, this.getTagDefinition, parseExpansionForms, interpolationConfig);
var /** @type {?} */ treeAndErrors = new _TreeBuilder(tokensAndErrors.tokens, this.getTagDefinition).build();
return new ParseTreeResult(treeAndErrors.rootNodes, ((tokensAndErrors.errors)).concat(treeAndErrors.errors));
};
return Parser$1;
}());
var _TreeBuilder = (function () {
/**
* @param {?} tokens
* @param {?} getTagDefinition
*/
function _TreeBuilder(tokens, getTagDefinition) {
this.tokens = tokens;
this.getTagDefinition = getTagDefinition;
this._index = -1;
this._rootNodes = [];
this._errors = [];
this._elementStack = [];
this._advance();
}
/**
* @return {?}
*/
_TreeBuilder.prototype.build = function () {
while (this._peek.type !== TokenType$1.EOF) {
if (this._peek.type === TokenType$1.TAG_OPEN_START) {
this._consumeStartTag(this._advance());
}
else if (this._peek.type === TokenType$1.TAG_CLOSE) {
this._consumeEndTag(this._advance());
}
else if (this._peek.type === TokenType$1.CDATA_START) {
this._closeVoidElement();
this._consumeCdata(this._advance());
}
else if (this._peek.type === TokenType$1.COMMENT_START) {
this._closeVoidElement();
this._consumeComment(this._advance());
}
else if (this._peek.type === TokenType$1.TEXT || this._peek.type === TokenType$1.RAW_TEXT ||
this._peek.type === TokenType$1.ESCAPABLE_RAW_TEXT) {
this._closeVoidElement();
this._consumeText(this._advance());
}
else if (this._peek.type === TokenType$1.EXPANSION_FORM_START) {
this._consumeExpansion(this._advance());
}
else {
// Skip all other tokens...
this._advance();
}
}
return new ParseTreeResult(this._rootNodes, this._errors);
};
/**
* @return {?}
*/
_TreeBuilder.prototype._advance = function () {
var /** @type {?} */ prev = this._peek;
if (this._index < this.tokens.length - 1) {
// Note: there is always an EOF token at the end
this._index++;
}
this._peek = this.tokens[this._index];
return prev;
};
/**
* @param {?} type
* @return {?}
*/
_TreeBuilder.prototype._advanceIf = function (type) {
if (this._peek.type === type) {
return this._advance();
}
return null;
};
/**
* @param {?} startToken
* @return {?}
*/
_TreeBuilder.prototype._consumeCdata = function (startToken) {
this._consumeText(this._advance());
this._advanceIf(TokenType$1.CDATA_END);
};
/**
* @param {?} token
* @return {?}
*/
_TreeBuilder.prototype._consumeComment = function (token) {
var /** @type {?} */ text = this._advanceIf(TokenType$1.RAW_TEXT);
this._advanceIf(TokenType$1.COMMENT_END);
var /** @type {?} */ value = text != null ? text.parts[0].trim() : null;
this._addToParent(new Comment(value, token.sourceSpan));
};
/**
* @param {?} token
* @return {?}
*/
_TreeBuilder.prototype._consumeExpansion = function (token) {
var /** @type {?} */ switchValue = this._advance();
var /** @type {?} */ type = this._advance();
var /** @type {?} */ cases = [];
// read =
while (this._peek.type === TokenType$1.EXPANSION_CASE_VALUE) {
var /** @type {?} */ expCase = this._parseExpansionCase();
if (!expCase)
return; // error
cases.push(expCase);
}
// read the final }
if (this._peek.type !== TokenType$1.EXPANSION_FORM_END) {
this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '}'."));
return;
}
var /** @type {?} */ sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end);
this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
this._advance();
};
/**
* @return {?}
*/
_TreeBuilder.prototype._parseExpansionCase = function () {
var /** @type {?} */ value = this._advance();
// read {
if (this._peek.type !== TokenType$1.EXPANSION_CASE_EXP_START) {
this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '{'."));
return null;
}
// read until }
var /** @type {?} */ start = this._advance();
var /** @type {?} */ exp = this._collectExpansionExpTokens(start);
if (!exp)
return null;
var /** @type {?} */ end = this._advance();
exp.push(new Token$1(TokenType$1.EOF, [], end.sourceSpan));
// parse everything in between { and }
var /** @type {?} */ parsedExp = new _TreeBuilder(exp, this.getTagDefinition).build();
if (parsedExp.errors.length > 0) {
this._errors = this._errors.concat(/** @type {?} */ (parsedExp.errors));
return null;
}
var /** @type {?} */ sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end);
var /** @type {?} */ expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end);
return new ExpansionCase(value.parts[0], parsedExp.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
};
/**
* @param {?} start
* @return {?}
*/
_TreeBuilder.prototype._collectExpansionExpTokens = function (start) {
var /** @type {?} */ exp = [];
var /** @type {?} */ expansionFormStack = [TokenType$1.EXPANSION_CASE_EXP_START];
while (true) {
if (this._peek.type === TokenType$1.EXPANSION_FORM_START ||
this._peek.type === TokenType$1.EXPANSION_CASE_EXP_START) {
expansionFormStack.push(this._peek.type);
}
if (this._peek.type === TokenType$1.EXPANSION_CASE_EXP_END) {
if (lastOnStack(expansionFormStack, TokenType$1.EXPANSION_CASE_EXP_START)) {
expansionFormStack.pop();
if (expansionFormStack.length == 0)
return exp;
}
else {
this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
return null;
}
}
if (this._peek.type === TokenType$1.EXPANSION_FORM_END) {
if (lastOnStack(expansionFormStack, TokenType$1.EXPANSION_FORM_START)) {
expansionFormStack.pop();
}
else {
this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
return null;
}
}
if (this._peek.type === TokenType$1.EOF) {
this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
return null;
}
exp.push(this._advance());
}
};
/**
* @param {?} token
* @return {?}
*/
_TreeBuilder.prototype._consumeText = function (token) {
var /** @type {?} */ text = token.parts[0];
if (text.length > 0 && text[0] == '\n') {
var /** @type {?} */ parent = this._getParentElement();
if (parent != null && parent.children.length == 0 &&
this.getTagDefinition(parent.name).ignoreFirstLf) {
text = text.substring(1);
}
}
if (text.length > 0) {
this._addToParent(new Text(text, token.sourceSpan));
}
};
/**
* @return {?}
*/
_TreeBuilder.prototype._closeVoidElement = function () {
if (this._elementStack.length > 0) {
var /** @type {?} */ el = this._elementStack[this._elementStack.length - 1];
if (this.getTagDefinition(el.name).isVoid) {
this._elementStack.pop();
}
}
};
/**
* @param {?} startTagToken
* @return {?}
*/
_TreeBuilder.prototype._consumeStartTag = function (startTagToken) {
var /** @type {?} */ prefix = startTagToken.parts[0];
var /** @type {?} */ name = startTagToken.parts[1];
var /** @type {?} */ attrs = [];
while (this._peek.type === TokenType$1.ATTR_NAME) {
attrs.push(this._consumeAttr(this._advance()));
}
var /** @type {?} */ fullName = this._getElementFullName(prefix, name, this._getParentElement());
var /** @type {?} */ selfClosing = false;
// Note: There could have been a tokenizer error
// so that we don't get a token for the end tag...
if (this._peek.type === TokenType$1.TAG_OPEN_END_VOID) {
this._advance();
selfClosing = true;
var /** @type {?} */ tagDef = this.getTagDefinition(fullName);
if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
this._errors.push(TreeError.create(fullName, startTagToken.sourceSpan, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\""));
}
}
else if (this._peek.type === TokenType$1.TAG_OPEN_END) {
this._advance();
selfClosing = false;
}
var /** @type {?} */ end = this._peek.sourceSpan.start;
var /** @type {?} */ span = new ParseSourceSpan(startTagToken.sourceSpan.start, end);
var /** @type {?} */ el = new Element(fullName, attrs, [], span, span, undefined);
this._pushElement(el);
if (selfClosing) {
this._popElement(fullName);
el.endSourceSpan = span;
}
};
/**
* @param {?} el
* @return {?}
*/
_TreeBuilder.prototype._pushElement = function (el) {
if (this._elementStack.length > 0) {
var /** @type {?} */ parentEl = this._elementStack[this._elementStack.length - 1];
if (this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
this._elementStack.pop();
}
}
var /** @type {?} */ tagDef = this.getTagDefinition(el.name);
var _a = this._getParentElementSkippingContainers(), parent = _a.parent, container = _a.container;
if (parent && tagDef.requireExtraParent(parent.name)) {
var /** @type {?} */ newParent = new Element(tagDef.parentToAdd, [], [], el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
this._insertBeforeContainer(parent, container, newParent);
}
this._addToParent(el);
this._elementStack.push(el);
};
/**
* @param {?} endTagToken
* @return {?}
*/
_TreeBuilder.prototype._consumeEndTag = function (endTagToken) {
var /** @type {?} */ fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
if (this._getParentElement()) {
((this._getParentElement())).endSourceSpan = endTagToken.sourceSpan;
}
if (this.getTagDefinition(fullName).isVoid) {
this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\""));
}
else if (!this._popElement(fullName)) {
var /** @type {?} */ errMsg = "Unexpected closing tag \"" + fullName + "\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags";
this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
}
};
/**
* @param {?} fullName
* @return {?}
*/
_TreeBuilder.prototype._popElement = function (fullName) {
for (var /** @type {?} */ stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
var /** @type {?} */ el = this._elementStack[stackIndex];
if (el.name == fullName) {
this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
return true;
}
if (!this.getTagDefinition(el.name).closedByParent) {
return false;
}
}
return false;
};
/**
* @param {?} attrName
* @return {?}
*/
_TreeBuilder.prototype._consumeAttr = function (attrName) {
var /** @type {?} */ fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
var /** @type {?} */ end = attrName.sourceSpan.end;
var /** @type {?} */ value = '';
var /** @type {?} */ valueSpan = ((undefined));
if (this._peek.type === TokenType$1.ATTR_VALUE) {
var /** @type {?} */ valueToken = this._advance();
value = valueToken.parts[0];
end = valueToken.sourceSpan.end;
valueSpan = valueToken.sourceSpan;
}
return new Attribute$1(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end), valueSpan);
};
/**
* @return {?}
*/
_TreeBuilder.prototype._getParentElement = function () {
return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
};
/**
* Returns the parent in the DOM and the container.
*
* `<ng-container>` elements are skipped as they are not rendered as DOM element.
* @return {?}
*/
_TreeBuilder.prototype._getParentElementSkippingContainers = function () {
var /** @type {?} */ container = null;
for (var /** @type {?} */ i = this._elementStack.length - 1; i >= 0; i--) {
if (!isNgContainer(this._elementStack[i].name)) {
return { parent: this._elementStack[i], container: container };
}
container = this._elementStack[i];
}
return { parent: this._elementStack[this._elementStack.length - 1], container: container };
};
/**
* @param {?} node
* @return {?}
*/
_TreeBuilder.prototype._addToParent = function (node) {
var /** @type {?} */ parent = this._getParentElement();
if (parent != null) {
parent.children.push(node);
}
else {
this._rootNodes.push(node);
}
};
/**
* Insert a node between the parent and the container.
* When no container is given, the node is appended as a child of the parent.
* Also updates the element stack accordingly.
*
* \@internal
* @param {?} parent
* @param {?} container
* @param {?} node
* @return {?}
*/
_TreeBuilder.prototype._insertBeforeContainer = function (parent, container, node) {
if (!container) {
this._addToParent(node);
this._elementStack.push(node);
}
else {
if (parent) {
// replace the container with the new node in the children
var /** @type {?} */ index = parent.children.indexOf(container);
parent.children[index] = node;
}
else {
this._rootNodes.push(node);
}
node.children.push(container);
this._elementStack.splice(this._elementStack.indexOf(container), 0, node);
}
};
/**
* @param {?} prefix
* @param {?} localName
* @param {?} parentElement
* @return {?}
*/
_TreeBuilder.prototype._getElementFullName = function (prefix, localName, parentElement) {
if (prefix == null) {
prefix = ((this.getTagDefinition(localName).implicitNamespacePrefix));
if (prefix == null && parentElement != null) {
prefix = getNsPrefix(parentElement.name);
}
}
return mergeNsAndName(prefix, localName);
};
return _TreeBuilder;
}());
/**
* @param {?} stack
* @param {?} element
* @return {?}
*/
function lastOnStack(stack, element) {
return stack.length > 0 && stack[stack.length - 1] === element;
}
/**
* @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
*/
var Message = (function () {
/**
* @param {?} nodes message AST
* @param {?} placeholders maps placeholder names to static content
* @param {?} placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
* @param {?} meaning
* @param {?} description
* @param {?} id
*/
function Message(nodes, placeholders, placeholderToMessage, meaning, description, id) {
this.nodes = nodes;
this.placeholders = placeholders;
this.placeholderToMessage = placeholderToMessage;
this.meaning = meaning;
this.description = description;
this.id = id;
if (nodes.length) {
this.sources = [{
filePath: nodes[0].sourceSpan.start.file.url,
startLine: nodes[0].sourceSpan.start.line + 1,
startCol: nodes[0].sourceSpan.start.col + 1,
endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
endCol: nodes[0].sourceSpan.start.col + 1
}];
}
else {
this.sources = [];
}
}
return Message;
}());
var Text$1 = (function () {
/**
* @param {?} value
* @param {?} sourceSpan
*/
function Text$1(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Text$1.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
return Text$1;
}());
var Container = (function () {
/**
* @param {?} children
* @param {?} sourceSpan
*/
function Container(children, sourceSpan) {
this.children = children;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Container.prototype.visit = function (visitor, context) { return visitor.visitContainer(this, context); };
return Container;
}());
var Icu = (function () {
/**
* @param {?} expression
* @param {?} type
* @param {?} cases
* @param {?} sourceSpan
*/
function Icu(expression, type, cases, sourceSpan) {
this.expression = expression;
this.type = type;
this.cases = cases;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Icu.prototype.visit = function (visitor, context) { return visitor.visitIcu(this, context); };
return Icu;
}());
var TagPlaceholder = (function () {
/**
* @param {?} tag
* @param {?} attrs
* @param {?} startName
* @param {?} closeName
* @param {?} children
* @param {?} isVoid
* @param {?} sourceSpan
*/
function TagPlaceholder(tag, attrs, startName, closeName, children, isVoid, sourceSpan) {
this.tag = tag;
this.attrs = attrs;
this.startName = startName;
this.closeName = closeName;
this.children = children;
this.isVoid = isVoid;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
TagPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitTagPlaceholder(this, context); };
return TagPlaceholder;
}());
var Placeholder = (function () {
/**
* @param {?} value
* @param {?} name
* @param {?} sourceSpan
*/
function Placeholder(value, name, sourceSpan) {
this.value = value;
this.name = name;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
Placeholder.prototype.visit = function (visitor, context) { return visitor.visitPlaceholder(this, context); };
return Placeholder;
}());
var IcuPlaceholder = (function () {
/**
* @param {?} value
* @param {?} name
* @param {?} sourceSpan
*/
function IcuPlaceholder(value, name, sourceSpan) {
this.value = value;
this.name = name;
this.sourceSpan = sourceSpan;
}
/**
* @param {?} visitor
* @param {?=} context
* @return {?}
*/
IcuPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitIcuPlaceholder(this, context); };
return IcuPlaceholder;
}());
var CloneVisitor = (function () {
function CloneVisitor() {
}
/**
* @param {?} text
* @param {?=} context
* @return {?}
*/
CloneVisitor.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
/**
* @param {?} container
* @param {?=} context
* @return {?}
*/
CloneVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
var /** @type {?} */ children = container.children.map(function (n) { return n.visit(_this, context); });
return new Container(children, container.sourceSpan);
};
/**
* @param {?} icu
* @param {?=} context
* @return {?}
*/
CloneVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var /** @type {?} */ cases = {};
Object.keys(icu.cases).forEach(function (key) { return cases[key] = icu.cases[key].visit(_this, context); });
var /** @type {?} */ msg = new Icu(icu.expression, icu.type, cases, icu.sourceSpan);
msg.expressionPlaceholder = icu.expressionPlaceholder;
return msg;
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
CloneVisitor.prototype.visitTagPlaceholder = function (ph, context) {
var _this = this;
var /** @type {?} */ children = ph.children.map(function (n) { return n.visit(_this, context); });
return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan);
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
CloneVisitor.prototype.visitPlaceholder = function (ph, context) {
return new Placeholder(ph.value, ph.name, ph.sourceSpan);
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
CloneVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
};
return CloneVisitor;
}());
var RecurseVisitor = (function () {
function RecurseVisitor() {
}
/**
* @param {?} text
* @param {?=} context
* @return {?}
*/
RecurseVisitor.prototype.visitText = function (text, context) { };
;
/**
* @param {?} container
* @param {?=} context
* @return {?}
*/
RecurseVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
container.children.forEach(function (child) { return child.visit(_this); });
};
/**
* @param {?} icu
* @param {?=} context
* @return {?}
*/
RecurseVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
Object.keys(icu.cases).forEach(function (k) { icu.cases[k].visit(_this); });
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
RecurseVisitor.prototype.visitTagPlaceholder = function (ph, context) {
var _this = this;
ph.children.forEach(function (child) { return child.visit(_this); });
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
RecurseVisitor.prototype.visitPlaceholder = function (ph, context) { };
;
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
RecurseVisitor.prototype.visitIcuPlaceholder = function (ph, context) { };
;
return RecurseVisitor;
}());
/**
* @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
*/
var TAG_TO_PLACEHOLDER_NAMES = {
'A': 'LINK',
'B': 'BOLD_TEXT',
'BR': 'LINE_BREAK',
'EM': 'EMPHASISED_TEXT',
'H1': 'HEADING_LEVEL1',
'H2': 'HEADING_LEVEL2',
'H3': 'HEADING_LEVEL3',
'H4': 'HEADING_LEVEL4',
'H5': 'HEADING_LEVEL5',
'H6': 'HEADING_LEVEL6',
'HR': 'HORIZONTAL_RULE',
'I': 'ITALIC_TEXT',
'LI': 'LIST_ITEM',
'LINK': 'MEDIA_LINK',
'OL': 'ORDERED_LIST',
'P': 'PARAGRAPH',
'Q': 'QUOTATION',
'S': 'STRIKETHROUGH_TEXT',
'SMALL': 'SMALL_TEXT',
'SUB': 'SUBSTRIPT',
'SUP': 'SUPERSCRIPT',
'TBODY': 'TABLE_BODY',
'TD': 'TABLE_CELL',
'TFOOT': 'TABLE_FOOTER',
'TH': 'TABLE_HEADER_CELL',
'THEAD': 'TABLE_HEADER',
'TR': 'TABLE_ROW',
'TT': 'MONOSPACED_TEXT',
'U': 'UNDERLINED_TEXT',
'UL': 'UNORDERED_LIST',
};
/**
* Creates unique names for placeholder with different content.
*
* Returns the same placeholder name when the content is identical.
*
* \@internal
*/
var PlaceholderRegistry = (function () {
function PlaceholderRegistry() {
this._placeHolderNameCounts = {};
this._signatureToName = {};
}
/**
* @param {?} tag
* @param {?} attrs
* @param {?} isVoid
* @return {?}
*/
PlaceholderRegistry.prototype.getStartTagPlaceholderName = function (tag, attrs, isVoid) {
var /** @type {?} */ signature = this._hashTag(tag, attrs, isVoid);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
var /** @type {?} */ upperTag = tag.toUpperCase();
var /** @type {?} */ baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
var /** @type {?} */ name = this._generateUniqueName(isVoid ? baseName : "START_" + baseName);
this._signatureToName[signature] = name;
return name;
};
/**
* @param {?} tag
* @return {?}
*/
PlaceholderRegistry.prototype.getCloseTagPlaceholderName = function (tag) {
var /** @type {?} */ signature = this._hashClosingTag(tag);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
var /** @type {?} */ upperTag = tag.toUpperCase();
var /** @type {?} */ baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
var /** @type {?} */ name = this._generateUniqueName("CLOSE_" + baseName);
this._signatureToName[signature] = name;
return name;
};
/**
* @param {?} name
* @param {?} content
* @return {?}
*/
PlaceholderRegistry.prototype.getPlaceholderName = function (name, content) {
var /** @type {?} */ upperName = name.toUpperCase();
var /** @type {?} */ signature = "PH: " + upperName + "=" + content;
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
var /** @type {?} */ uniqueName = this._generateUniqueName(upperName);
this._signatureToName[signature] = uniqueName;
return uniqueName;
};
/**
* @param {?} name
* @return {?}
*/
PlaceholderRegistry.prototype.getUniquePlaceholder = function (name) {
return this._generateUniqueName(name.toUpperCase());
};
/**
* @param {?} tag
* @param {?} attrs
* @param {?} isVoid
* @return {?}
*/
PlaceholderRegistry.prototype._hashTag = function (tag, attrs, isVoid) {
var /** @type {?} */ start = "<" + tag;
var /** @type {?} */ strAttrs = Object.keys(attrs).sort().map(function (name) { return " " + name + "=" + attrs[name]; }).join('');
var /** @type {?} */ end = isVoid ? '/>' : "></" + tag + ">";
return start + strAttrs + end;
};
/**
* @param {?} tag
* @return {?}
*/
PlaceholderRegistry.prototype._hashClosingTag = function (tag) { return this._hashTag("/" + tag, {}, false); };
/**
* @param {?} base
* @return {?}
*/
PlaceholderRegistry.prototype._generateUniqueName = function (base) {
var /** @type {?} */ seen = this._placeHolderNameCounts.hasOwnProperty(base);
if (!seen) {
this._placeHolderNameCounts[base] = 1;
return base;
}
var /** @type {?} */ id = this._placeHolderNameCounts[base];
this._placeHolderNameCounts[base] = id + 1;
return base + "_" + id;
};
return PlaceholderRegistry;
}());
/**
* @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
*/
var _expParser = new Parser(new Lexer());
/**
* Returns a function converting html nodes to an i18n Message given an interpolationConfig
* @param {?} interpolationConfig
* @return {?}
*/
function createI18nMessageFactory(interpolationConfig) {
var /** @type {?} */ visitor = new _I18nVisitor(_expParser, interpolationConfig);
return function (nodes, meaning, description, id) { return visitor.toI18nMessage(nodes, meaning, description, id); };
}
var _I18nVisitor = (function () {
/**
* @param {?} _expressionParser
* @param {?} _interpolationConfig
*/
function _I18nVisitor(_expressionParser, _interpolationConfig) {
this._expressionParser = _expressionParser;
this._interpolationConfig = _interpolationConfig;
}
/**
* @param {?} nodes
* @param {?} meaning
* @param {?} description
* @param {?} id
* @return {?}
*/
_I18nVisitor.prototype.toI18nMessage = function (nodes, meaning, description, id) {
this._isIcu = nodes.length == 1 && nodes[0] instanceof Expansion;
this._icuDepth = 0;
this._placeholderRegistry = new PlaceholderRegistry();
this._placeholderToContent = {};
this._placeholderToMessage = {};
var /** @type {?} */ i18nodes = visitAll(this, nodes, {});
return new Message(i18nodes, this._placeholderToContent, this._placeholderToMessage, meaning, description, id);
};
/**
* @param {?} el
* @param {?} context
* @return {?}
*/
_I18nVisitor.prototype.visitElement = function (el, context) {
var /** @type {?} */ children = visitAll(this, el.children);
var /** @type {?} */ attrs = {};
el.attrs.forEach(function (attr) {
// Do not visit the attributes, translatable ones are top-level ASTs
attrs[attr.name] = attr.value;
});
var /** @type {?} */ isVoid = getHtmlTagDefinition(el.name).isVoid;
var /** @type {?} */ startPhName = this._placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
this._placeholderToContent[startPhName] = ((el.sourceSpan)).toString();
var /** @type {?} */ closePhName = '';
if (!isVoid) {
closePhName = this._placeholderRegistry.getCloseTagPlaceholderName(el.name);
this._placeholderToContent[closePhName] = "</" + el.name + ">";
}
return new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, /** @type {?} */ ((el.sourceSpan)));
};
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
_I18nVisitor.prototype.visitAttribute = function (attribute, context) {
return this._visitTextWithInterpolation(attribute.value, attribute.sourceSpan);
};
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
_I18nVisitor.prototype.visitText = function (text, context) {
return this._visitTextWithInterpolation(text.value, /** @type {?} */ ((text.sourceSpan)));
};
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
_I18nVisitor.prototype.visitComment = function (comment, context) { return null; };
/**
* @param {?} icu
* @param {?} context
* @return {?}
*/
_I18nVisitor.prototype.visitExpansion = function (icu, context) {
var _this = this;
this._icuDepth++;
var /** @type {?} */ i18nIcuCases = {};
var /** @type {?} */ i18nIcu = new Icu(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
icu.cases.forEach(function (caze) {
i18nIcuCases[caze.value] = new Container(caze.expression.map(function (node) { return node.visit(_this, {}); }), caze.expSourceSpan);
});
this._icuDepth--;
if (this._isIcu || this._icuDepth > 0) {
// Returns an ICU node when:
// - the message (vs a part of the message) is an ICU message, or
// - the ICU message is nested.
var /** @type {?} */ expPh = this._placeholderRegistry.getUniquePlaceholder("VAR_" + icu.type);
i18nIcu.expressionPlaceholder = expPh;
this._placeholderToContent[expPh] = icu.switchValue;
return i18nIcu;
}
// Else returns a placeholder
// ICU placeholders should not be replaced with their original content but with the their
// translations. We need to create a new visitor (they are not re-entrant) to compute the
// message id.
// TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
var /** @type {?} */ phName = this._placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
var /** @type {?} */ visitor = new _I18nVisitor(this._expressionParser, this._interpolationConfig);
this._placeholderToMessage[phName] = visitor.toI18nMessage([icu], '', '', '');
return new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
};
/**
* @param {?} icuCase
* @param {?} context
* @return {?}
*/
_I18nVisitor.prototype.visitExpansionCase = function (icuCase, context) {
throw new Error('Unreachable code');
};
/**
* @param {?} text
* @param {?} sourceSpan
* @return {?}
*/
_I18nVisitor.prototype._visitTextWithInterpolation = function (text, sourceSpan) {
var /** @type {?} */ splitInterpolation = this._expressionParser.splitInterpolation(text, sourceSpan.start.toString(), this._interpolationConfig);
if (!splitInterpolation) {
// No expression, return a single text
return new Text$1(text, sourceSpan);
}
// Return a group of text + expressions
var /** @type {?} */ nodes = [];
var /** @type {?} */ container = new Container(nodes, sourceSpan);
var _a = this._interpolationConfig, sDelimiter = _a.start, eDelimiter = _a.end;
for (var /** @type {?} */ i = 0; i < splitInterpolation.strings.length - 1; i++) {
var /** @type {?} */ expression = splitInterpolation.expressions[i];
var /** @type {?} */ baseName = _extractPlaceholderName(expression) || 'INTERPOLATION';
var /** @type {?} */ phName = this._placeholderRegistry.getPlaceholderName(baseName, expression);
if (splitInterpolation.strings[i].length) {
// No need to add empty strings
nodes.push(new Text$1(splitInterpolation.strings[i], sourceSpan));
}
nodes.push(new Placeholder(expression, phName, sourceSpan));
this._placeholderToContent[phName] = sDelimiter + expression + eDelimiter;
}
// The last index contains no expression
var /** @type {?} */ lastStringIdx = splitInterpolation.strings.length - 1;
if (splitInterpolation.strings[lastStringIdx].length) {
nodes.push(new Text$1(splitInterpolation.strings[lastStringIdx], sourceSpan));
}
return container;
};
return _I18nVisitor;
}());
var _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
/**
* @param {?} input
* @return {?}
*/
function _extractPlaceholderName(input) {
return input.split(_CUSTOM_PH_EXP)[2];
}
/**
* @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
*/
/**
* An i18n error.
*/
var I18nError = (function (_super) {
__extends(I18nError, _super);
/**
* @param {?} span
* @param {?} msg
*/
function I18nError(span, msg) {
return _super.call(this, span, msg) || this;
}
return I18nError;
}(ParseError));
/**
* @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
*/
var _I18N_ATTR = 'i18n';
var _I18N_ATTR_PREFIX = 'i18n-';
var _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
var MEANING_SEPARATOR = '|';
var ID_SEPARATOR = '@@';
/**
* Extract translatable messages from an html AST
* @param {?} nodes
* @param {?} interpolationConfig
* @param {?} implicitTags
* @param {?} implicitAttrs
* @return {?}
*/
function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) {
var /** @type {?} */ visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.extract(nodes, interpolationConfig);
}
/**
* @param {?} nodes
* @param {?} translations
* @param {?} interpolationConfig
* @param {?} implicitTags
* @param {?} implicitAttrs
* @return {?}
*/
function mergeTranslations(nodes, translations, interpolationConfig, implicitTags, implicitAttrs) {
var /** @type {?} */ visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.merge(nodes, translations, interpolationConfig);
}
var ExtractionResult = (function () {
/**
* @param {?} messages
* @param {?} errors
*/
function ExtractionResult(messages, errors) {
this.messages = messages;
this.errors = errors;
}
return ExtractionResult;
}());
var _VisitorMode = {};
_VisitorMode.Extract = 0;
_VisitorMode.Merge = 1;
_VisitorMode[_VisitorMode.Extract] = "Extract";
_VisitorMode[_VisitorMode.Merge] = "Merge";
/**
* This Visitor is used:
* 1. to extract all the translatable strings from an html AST (see `extract()`),
* 2. to replace the translatable strings with the actual translations (see `merge()`)
*
* \@internal
*/
var _Visitor = (function () {
/**
* @param {?} _implicitTags
* @param {?} _implicitAttrs
*/
function _Visitor(_implicitTags, _implicitAttrs) {
this._implicitTags = _implicitTags;
this._implicitAttrs = _implicitAttrs;
}
/**
* Extracts the messages from the tree
* @param {?} nodes
* @param {?} interpolationConfig
* @return {?}
*/
_Visitor.prototype.extract = function (nodes, interpolationConfig) {
var _this = this;
this._init(_VisitorMode.Extract, interpolationConfig);
nodes.forEach(function (node) { return node.visit(_this, null); });
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ExtractionResult(this._messages, this._errors);
};
/**
* Returns a tree where all translatable nodes are translated
* @param {?} nodes
* @param {?} translations
* @param {?} interpolationConfig
* @return {?}
*/
_Visitor.prototype.merge = function (nodes, translations, interpolationConfig) {
this._init(_VisitorMode.Merge, interpolationConfig);
this._translations = translations;
// Construct a single fake root element
var /** @type {?} */ wrapper = new Element('wrapper', [], nodes, /** @type {?} */ ((undefined)), undefined, undefined);
var /** @type {?} */ translatedNode = wrapper.visit(this, null);
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ParseTreeResult(translatedNode.children, this._errors);
};
/**
* @param {?} icuCase
* @param {?} context
* @return {?}
*/
_Visitor.prototype.visitExpansionCase = function (icuCase, context) {
// Parse cases for translatable html attributes
var /** @type {?} */ expression = visitAll(this, icuCase.expression, context);
if (this._mode === _VisitorMode.Merge) {
return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
}
};
/**
* @param {?} icu
* @param {?} context
* @return {?}
*/
_Visitor.prototype.visitExpansion = function (icu, context) {
this._mayBeAddBlockChildren(icu);
var /** @type {?} */ wasInIcu = this._inIcu;
if (!this._inIcu) {
// nested ICU messages should not be extracted but top-level translated as a whole
if (this._isInTranslatableSection) {
this._addMessage([icu]);
}
this._inIcu = true;
}
var /** @type {?} */ cases = visitAll(this, icu.cases, context);
if (this._mode === _VisitorMode.Merge) {
icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
}
this._inIcu = wasInIcu;
return icu;
};
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
_Visitor.prototype.visitComment = function (comment, context) {
var /** @type {?} */ isOpening = _isOpeningComment(comment);
if (isOpening && this._isInTranslatableSection) {
this._reportError(comment, 'Could not start a block inside a translatable section');
return;
}
var /** @type {?} */ isClosing = _isClosingComment(comment);
if (isClosing && !this._inI18nBlock) {
this._reportError(comment, 'Trying to close an unopened block');
return;
}
if (!this._inI18nNode && !this._inIcu) {
if (!this._inI18nBlock) {
if (isOpening) {
this._inI18nBlock = true;
this._blockStartDepth = this._depth;
this._blockChildren = [];
this._blockMeaningAndDesc = ((comment.value)).replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
this._openTranslatableSection(comment);
}
}
else {
if (isClosing) {
if (this._depth == this._blockStartDepth) {
this._closeTranslatableSection(comment, this._blockChildren);
this._inI18nBlock = false;
var /** @type {?} */ message = ((this._addMessage(this._blockChildren, this._blockMeaningAndDesc)));
// merge attributes in sections
var /** @type {?} */ nodes = this._translateMessage(comment, message);
return visitAll(this, nodes);
}
else {
this._reportError(comment, 'I18N blocks should not cross element boundaries');
return;
}
}
}
}
};
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
_Visitor.prototype.visitText = function (text, context) {
if (this._isInTranslatableSection) {
this._mayBeAddBlockChildren(text);
}
return text;
};
/**
* @param {?} el
* @param {?} context
* @return {?}
*/
_Visitor.prototype.visitElement = function (el, context) {
var _this = this;
this._mayBeAddBlockChildren(el);
this._depth++;
var /** @type {?} */ wasInI18nNode = this._inI18nNode;
var /** @type {?} */ wasInImplicitNode = this._inImplicitNode;
var /** @type {?} */ childNodes = [];
var /** @type {?} */ translatedChildNodes = ((undefined));
// Extract:
// - top level nodes with the (implicit) "i18n" attribute if not already in a section
// - ICU messages
var /** @type {?} */ i18nAttr = _getI18nAttr(el);
var /** @type {?} */ i18nMeta = i18nAttr ? i18nAttr.value : '';
var /** @type {?} */ isImplicit = this._implicitTags.some(function (tag) { return el.name === tag; }) && !this._inIcu &&
!this._isInTranslatableSection;
var /** @type {?} */ isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this._inImplicitNode = wasInImplicitNode || isImplicit;
if (!this._isInTranslatableSection && !this._inIcu) {
if (i18nAttr || isTopLevelImplicit) {
this._inI18nNode = true;
var /** @type {?} */ message = ((this._addMessage(el.children, i18nMeta)));
translatedChildNodes = this._translateMessage(el, message);
}
if (this._mode == _VisitorMode.Extract) {
var /** @type {?} */ isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable)
this._openTranslatableSection(el);
visitAll(this, el.children);
if (isTranslatable)
this._closeTranslatableSection(el, el.children);
}
}
else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(el, 'Could not mark an element as translatable inside a translatable section');
}
if (this._mode == _VisitorMode.Extract) {
// Descend into child nodes for extraction
visitAll(this, el.children);
}
}
if (this._mode === _VisitorMode.Merge) {
var /** @type {?} */ visitNodes = translatedChildNodes || el.children;
visitNodes.forEach(function (child) {
var /** @type {?} */ visited = child.visit(_this, context);
if (visited && !_this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
this._visitAttributesOf(el);
this._depth--;
this._inI18nNode = wasInI18nNode;
this._inImplicitNode = wasInImplicitNode;
if (this._mode === _VisitorMode.Merge) {
var /** @type {?} */ translatedAttrs = this._translateAttributes(el);
return new Element(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
}
return null;
};
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
_Visitor.prototype.visitAttribute = function (attribute, context) {
throw new Error('unreachable code');
};
/**
* @param {?} mode
* @param {?} interpolationConfig
* @return {?}
*/
_Visitor.prototype._init = function (mode, interpolationConfig) {
this._mode = mode;
this._inI18nBlock = false;
this._inI18nNode = false;
this._depth = 0;
this._inIcu = false;
this._msgCountAtSectionStart = undefined;
this._errors = [];
this._messages = [];
this._inImplicitNode = false;
this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
};
/**
* @param {?} el
* @return {?}
*/
_Visitor.prototype._visitAttributesOf = function (el) {
var _this = this;
var /** @type {?} */ explicitAttrNameToValue = {};
var /** @type {?} */ implicitAttrNames = this._implicitAttrs[el.name] || [];
el.attrs.filter(function (attr) { return attr.name.startsWith(_I18N_ATTR_PREFIX); })
.forEach(function (attr) { return explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
attr.value; });
el.attrs.forEach(function (attr) {
if (attr.name in explicitAttrNameToValue) {
_this._addMessage([attr], explicitAttrNameToValue[attr.name]);
}
else if (implicitAttrNames.some(function (name) { return attr.name === name; })) {
_this._addMessage([attr]);
}
});
};
/**
* @param {?} ast
* @param {?=} msgMeta
* @return {?}
*/
_Visitor.prototype._addMessage = function (ast, msgMeta) {
if (ast.length == 0 ||
ast.length == 1 && ast[0] instanceof Attribute$1 && !((ast[0])).value) {
// Do not create empty messages
return null;
}
var _a = _parseMessageMeta(msgMeta), meaning = _a.meaning, description = _a.description, id = _a.id;
var /** @type {?} */ message = this._createI18nMessage(ast, meaning, description, id);
this._messages.push(message);
return message;
};
/**
* @param {?} el
* @param {?} message
* @return {?}
*/
_Visitor.prototype._translateMessage = function (el, message) {
if (message && this._mode === _VisitorMode.Merge) {
var /** @type {?} */ nodes = this._translations.get(message);
if (nodes) {
return nodes;
}
this._reportError(el, "Translation unavailable for message id=\"" + this._translations.digest(message) + "\"");
}
return [];
};
/**
* @param {?} el
* @return {?}
*/
_Visitor.prototype._translateAttributes = function (el) {
var _this = this;
var /** @type {?} */ attributes = el.attrs;
var /** @type {?} */ i18nParsedMessageMeta = {};
attributes.forEach(function (attr) {
if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
_parseMessageMeta(attr.value);
}
});
var /** @type {?} */ translatedAttributes = [];
attributes.forEach(function (attr) {
if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
// strip i18n specific attributes
return;
}
if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
var _a = i18nParsedMessageMeta[attr.name], meaning = _a.meaning, description = _a.description, id = _a.id;
var /** @type {?} */ message = _this._createI18nMessage([attr], meaning, description, id);
var /** @type {?} */ nodes = _this._translations.get(message);
if (nodes) {
if (nodes.length == 0) {
translatedAttributes.push(new Attribute$1(attr.name, '', attr.sourceSpan));
}
else if (nodes[0] instanceof Text) {
var /** @type {?} */ value = ((nodes[0])).value;
translatedAttributes.push(new Attribute$1(attr.name, value, attr.sourceSpan));
}
else {
_this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
}
}
else {
_this._reportError(el, "Translation unavailable for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
}
}
else {
translatedAttributes.push(attr);
}
});
return translatedAttributes;
};
/**
* Add the node as a child of the block when:
* - we are in a block,
* - we are not inside a ICU message (those are handled separately),
* - the node is a "direct child" of the block
* @param {?} node
* @return {?}
*/
_Visitor.prototype._mayBeAddBlockChildren = function (node) {
if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
this._blockChildren.push(node);
}
};
/**
* Marks the start of a section, see `_closeTranslatableSection`
* @param {?} node
* @return {?}
*/
_Visitor.prototype._openTranslatableSection = function (node) {
if (this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section start');
}
else {
this._msgCountAtSectionStart = this._messages.length;
}
};
Object.defineProperty(_Visitor.prototype, "_isInTranslatableSection", {
/**
* A translatable section could be:
* - the content of translatable element,
* - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
* @return {?}
*/
get: function () {
return this._msgCountAtSectionStart !== void 0;
},
enumerable: true,
configurable: true
});
/**
* Terminates a section.
*
* If a section has only one significant children (comments not significant) then we should not
* keep the message from this children:
*
* `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
* - one for the <p> content with meaning and description,
* - another one for the ICU message.
*
* In this case the last message is discarded as it contains less information (the AST is
* otherwise identical).
*
* Note that we should still keep messages extracted from attributes inside the section (ie in the
* ICU message here)
* @param {?} node
* @param {?} directChildren
* @return {?}
*/
_Visitor.prototype._closeTranslatableSection = function (node, directChildren) {
if (!this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section end');
return;
}
var /** @type {?} */ startIndex = this._msgCountAtSectionStart;
var /** @type {?} */ significantChildren = directChildren.reduce(function (count, node) { return count + (node instanceof Comment ? 0 : 1); }, 0);
if (significantChildren == 1) {
for (var /** @type {?} */ i = this._messages.length - 1; i >= startIndex; i--) {
var /** @type {?} */ ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = undefined;
};
/**
* @param {?} node
* @param {?} msg
* @return {?}
*/
_Visitor.prototype._reportError = function (node, msg) {
this._errors.push(new I18nError(/** @type {?} */ ((node.sourceSpan)), msg));
};
return _Visitor;
}());
/**
* @param {?} n
* @return {?}
*/
function _isOpeningComment(n) {
return !!(n instanceof Comment && n.value && n.value.startsWith('i18n'));
}
/**
* @param {?} n
* @return {?}
*/
function _isClosingComment(n) {
return !!(n instanceof Comment && n.value && n.value === '/i18n');
}
/**
* @param {?} p
* @return {?}
*/
function _getI18nAttr(p) {
return p.attrs.find(function (attr) { return attr.name === _I18N_ATTR; }) || null;
}
/**
* @param {?=} i18n
* @return {?}
*/
function _parseMessageMeta(i18n) {
if (!i18n)
return { meaning: '', description: '', id: '' };
var /** @type {?} */ idIndex = i18n.indexOf(ID_SEPARATOR);
var /** @type {?} */ descIndex = i18n.indexOf(MEANING_SEPARATOR);
var _a = (idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''], meaningAndDesc = _a[0], id = _a[1];
var _b = (descIndex > -1) ?
[meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
['', meaningAndDesc], meaning = _b[0], description = _b[1];
return { meaning: meaning, description: description, id: id };
}
/**
* @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
*/
var XmlTagDefinition = (function () {
function XmlTagDefinition() {
this.closedByParent = false;
this.contentType = TagContentType.PARSABLE_DATA;
this.isVoid = false;
this.ignoreFirstLf = false;
this.canSelfClose = true;
}
/**
* @param {?} currentParent
* @return {?}
*/
XmlTagDefinition.prototype.requireExtraParent = function (currentParent) { return false; };
/**
* @param {?} name
* @return {?}
*/
XmlTagDefinition.prototype.isClosedByChild = function (name) { return false; };
return XmlTagDefinition;
}());
var _TAG_DEFINITION = new XmlTagDefinition();
/**
* @param {?} tagName
* @return {?}
*/
function getXmlTagDefinition(tagName) {
return _TAG_DEFINITION;
}
/**
* @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
*/
var XmlParser = (function (_super) {
__extends(XmlParser, _super);
function XmlParser() {
return _super.call(this, getXmlTagDefinition) || this;
}
/**
* @param {?} source
* @param {?} url
* @param {?=} parseExpansionForms
* @return {?}
*/
XmlParser.prototype.parse = function (source, url, parseExpansionForms) {
if (parseExpansionForms === void 0) { parseExpansionForms = false; }
return _super.prototype.parse.call(this, source, url, parseExpansionForms);
};
return XmlParser;
}(Parser$1));
/**
* @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
*/
/**
* @param {?} message
* @return {?}
*/
function digest(message) {
return message.id || sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]"));
}
/**
* @param {?} message
* @return {?}
*/
function decimalDigest(message) {
if (message.id) {
return message.id;
}
var /** @type {?} */ visitor = new _SerializerIgnoreIcuExpVisitor();
var /** @type {?} */ parts = message.nodes.map(function (a) { return a.visit(visitor, null); });
return computeMsgId(parts.join(''), message.meaning);
}
/**
* Serialize the i18n ast to something xml-like in order to generate an UID.
*
* The visitor is also used in the i18n parser tests
*
* \@internal
*/
var _SerializerVisitor = (function () {
function _SerializerVisitor() {
}
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
_SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
/**
* @param {?} container
* @param {?} context
* @return {?}
*/
_SerializerVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
return "[" + container.children.map(function (child) { return child.visit(_this); }).join(', ') + "]";
};
/**
* @param {?} icu
* @param {?} context
* @return {?}
*/
_SerializerVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var /** @type {?} */ strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
return "{" + icu.expression + ", " + icu.type + ", " + strCases.join(', ') + "}";
};
/**
* @param {?} ph
* @param {?} context
* @return {?}
*/
_SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
var _this = this;
return ph.isVoid ?
"<ph tag name=\"" + ph.startName + "\"/>" :
"<ph tag name=\"" + ph.startName + "\">" + ph.children.map(function (child) { return child.visit(_this); }).join(', ') + "</ph name=\"" + ph.closeName + "\">";
};
/**
* @param {?} ph
* @param {?} context
* @return {?}
*/
_SerializerVisitor.prototype.visitPlaceholder = function (ph, context) {
return ph.value ? "<ph name=\"" + ph.name + "\">" + ph.value + "</ph>" : "<ph name=\"" + ph.name + "\"/>";
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
return "<ph icu name=\"" + ph.name + "\">" + ph.value.visit(this) + "</ph>";
};
return _SerializerVisitor;
}());
var serializerVisitor = new _SerializerVisitor();
/**
* @param {?} nodes
* @return {?}
*/
function serializeNodes(nodes) {
return nodes.map(function (a) { return a.visit(serializerVisitor, null); });
}
/**
* Serialize the i18n ast to something xml-like in order to generate an UID.
*
* Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
*
* \@internal
*/
var _SerializerIgnoreIcuExpVisitor = (function (_super) {
__extends(_SerializerIgnoreIcuExpVisitor, _super);
function _SerializerIgnoreIcuExpVisitor() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} icu
* @param {?} context
* @return {?}
*/
_SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var /** @type {?} */ strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
// Do not take the expression into account
return "{" + icu.type + ", " + strCases.join(', ') + "}";
};
return _SerializerIgnoreIcuExpVisitor;
}(_SerializerVisitor));
/**
* Compute the SHA1 of the given string
*
* see http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
*
* WARNING: this function has not been designed not tested with security in mind.
* DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
* @param {?} str
* @return {?}
*/
function sha1(str) {
var /** @type {?} */ utf8 = utf8Encode(str);
var /** @type {?} */ words32 = stringToWords32(utf8, Endian.Big);
var /** @type {?} */ len = utf8.length * 8;
var /** @type {?} */ w = new Array(80);
var _a = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0], a = _a[0], b = _a[1], c = _a[2], d = _a[3], e = _a[4];
words32[len >> 5] |= 0x80 << (24 - len % 32);
words32[((len + 64 >> 9) << 4) + 15] = len;
for (var /** @type {?} */ i = 0; i < words32.length; i += 16) {
var _b = [a, b, c, d, e], h0 = _b[0], h1 = _b[1], h2 = _b[2], h3 = _b[3], h4 = _b[4];
for (var /** @type {?} */ j = 0; j < 80; j++) {
if (j < 16) {
w[j] = words32[i + j];
}
else {
w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
}
var _c = fk(j, b, c, d), f = _c[0], k = _c[1];
var /** @type {?} */ temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
_d = [d, c, rol32(b, 30), a, temp], e = _d[0], d = _d[1], c = _d[2], b = _d[3], a = _d[4];
}
_e = [add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)], a = _e[0], b = _e[1], c = _e[2], d = _e[3], e = _e[4];
}
return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
var _d, _e;
}
/**
* @param {?} index
* @param {?} b
* @param {?} c
* @param {?} d
* @return {?}
*/
function fk(index, b, c, d) {
if (index < 20) {
return [(b & c) | (~b & d), 0x5a827999];
}
if (index < 40) {
return [b ^ c ^ d, 0x6ed9eba1];
}
if (index < 60) {
return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
}
return [b ^ c ^ d, 0xca62c1d6];
}
/**
* Compute the fingerprint of the given string
*
* The output is 64 bit number encoded as a decimal string
*
* based on:
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
* @param {?} str
* @return {?}
*/
function fingerprint(str) {
var /** @type {?} */ utf8 = utf8Encode(str);
var _a = [hash32(utf8, 0), hash32(utf8, 102072)], hi = _a[0], lo = _a[1];
if (hi == 0 && (lo == 0 || lo == 1)) {
hi = hi ^ 0x130f9bef;
lo = lo ^ -0x6b5f56d8;
}
return [hi, lo];
}
/**
* @param {?} msg
* @param {?} meaning
* @return {?}
*/
function computeMsgId(msg, meaning) {
var _a = fingerprint(msg), hi = _a[0], lo = _a[1];
if (meaning) {
var _b = fingerprint(meaning), him = _b[0], lom = _b[1];
_c = add64(rol64([hi, lo], 1), [him, lom]), hi = _c[0], lo = _c[1];
}
return byteStringToDecString(words32ToByteString([hi & 0x7fffffff, lo]));
var _c;
}
/**
* @param {?} str
* @param {?} c
* @return {?}
*/
function hash32(str, c) {
var _a = [0x9e3779b9, 0x9e3779b9], a = _a[0], b = _a[1];
var /** @type {?} */ i;
var /** @type {?} */ len = str.length;
for (i = 0; i + 12 <= len; i += 12) {
a = add32(a, wordAt(str, i, Endian.Little));
b = add32(b, wordAt(str, i + 4, Endian.Little));
c = add32(c, wordAt(str, i + 8, Endian.Little));
_b = mix([a, b, c]), a = _b[0], b = _b[1], c = _b[2];
}
a = add32(a, wordAt(str, i, Endian.Little));
b = add32(b, wordAt(str, i + 4, Endian.Little));
// the first byte of c is reserved for the length
c = add32(c, len);
c = add32(c, wordAt(str, i + 8, Endian.Little) << 8);
return mix([a, b, c])[2];
var _b;
}
/**
* @param {?} __0
* @return {?}
*/
function mix(_a) {
var a = _a[0], b = _a[1], c = _a[2];
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 13;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 8;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 13;
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 12;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 16;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 5;
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 3;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 10;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 15;
return [a, b, c];
}
var Endian = {};
Endian.Little = 0;
Endian.Big = 1;
Endian[Endian.Little] = "Little";
Endian[Endian.Big] = "Big";
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function add32(a, b) {
return add32to64(a, b)[1];
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function add32to64(a, b) {
var /** @type {?} */ low = (a & 0xffff) + (b & 0xffff);
var /** @type {?} */ high = (a >>> 16) + (b >>> 16) + (low >>> 16);
return [high >>> 16, (high << 16) | (low & 0xffff)];
}
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function add64(_a, _b) {
var ah = _a[0], al = _a[1];
var bh = _b[0], bl = _b[1];
var _c = add32to64(al, bl), carry = _c[0], l = _c[1];
var /** @type {?} */ h = add32(add32(ah, bh), carry);
return [h, l];
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function sub32(a, b) {
var /** @type {?} */ low = (a & 0xffff) - (b & 0xffff);
var /** @type {?} */ high = (a >> 16) - (b >> 16) + (low >> 16);
return (high << 16) | (low & 0xffff);
}
/**
* @param {?} a
* @param {?} count
* @return {?}
*/
function rol32(a, count) {
return (a << count) | (a >>> (32 - count));
}
/**
* @param {?} __0
* @param {?} count
* @return {?}
*/
function rol64(_a, count) {
var hi = _a[0], lo = _a[1];
var /** @type {?} */ h = (hi << count) | (lo >>> (32 - count));
var /** @type {?} */ l = (lo << count) | (hi >>> (32 - count));
return [h, l];
}
/**
* @param {?} str
* @param {?} endian
* @return {?}
*/
function stringToWords32(str, endian) {
var /** @type {?} */ words32 = Array((str.length + 3) >>> 2);
for (var /** @type {?} */ i = 0; i < words32.length; i++) {
words32[i] = wordAt(str, i * 4, endian);
}
return words32;
}
/**
* @param {?} str
* @param {?} index
* @return {?}
*/
function byteAt(str, index) {
return index >= str.length ? 0 : str.charCodeAt(index) & 0xff;
}
/**
* @param {?} str
* @param {?} index
* @param {?} endian
* @return {?}
*/
function wordAt(str, index, endian) {
var /** @type {?} */ word = 0;
if (endian === Endian.Big) {
for (var /** @type {?} */ i = 0; i < 4; i++) {
word += byteAt(str, index + i) << (24 - 8 * i);
}
}
else {
for (var /** @type {?} */ i = 0; i < 4; i++) {
word += byteAt(str, index + i) << 8 * i;
}
}
return word;
}
/**
* @param {?} words32
* @return {?}
*/
function words32ToByteString(words32) {
return words32.reduce(function (str, word) { return str + word32ToByteString(word); }, '');
}
/**
* @param {?} word
* @return {?}
*/
function word32ToByteString(word) {
var /** @type {?} */ str = '';
for (var /** @type {?} */ i = 0; i < 4; i++) {
str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff);
}
return str;
}
/**
* @param {?} str
* @return {?}
*/
function byteStringToHexString(str) {
var /** @type {?} */ hex = '';
for (var /** @type {?} */ i = 0; i < str.length; i++) {
var /** @type {?} */ b = byteAt(str, i);
hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
}
return hex.toLowerCase();
}
/**
* @param {?} str
* @return {?}
*/
function byteStringToDecString(str) {
var /** @type {?} */ decimal = '';
var /** @type {?} */ toThePower = '1';
for (var /** @type {?} */ i = str.length - 1; i >= 0; i--) {
decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower));
toThePower = numberTimesBigInt(256, toThePower);
}
return decimal.split('').reverse().join('');
}
/**
* @param {?} x
* @param {?} y
* @return {?}
*/
function addBigInt(x, y) {
var /** @type {?} */ sum = '';
var /** @type {?} */ len = Math.max(x.length, y.length);
for (var /** @type {?} */ i = 0, /** @type {?} */ carry = 0; i < len || carry; i++) {
var /** @type {?} */ tmpSum = carry + +(x[i] || 0) + +(y[i] || 0);
if (tmpSum >= 10) {
carry = 1;
sum += tmpSum - 10;
}
else {
carry = 0;
sum += tmpSum;
}
}
return sum;
}
/**
* @param {?} num
* @param {?} b
* @return {?}
*/
function numberTimesBigInt(num, b) {
var /** @type {?} */ product = '';
var /** @type {?} */ bToThePower = b;
for (; num !== 0; num = num >>> 1) {
if (num & 1)
product = addBigInt(product, bToThePower);
bToThePower = addBigInt(bToThePower, bToThePower);
}
return product;
}
/**
* @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
*/
/**
* @abstract
*/
var Serializer = (function () {
function Serializer() {
}
/**
* @abstract
* @param {?} messages
* @param {?} locale
* @return {?}
*/
Serializer.prototype.write = function (messages, locale) { };
/**
* @abstract
* @param {?} content
* @param {?} url
* @return {?}
*/
Serializer.prototype.load = function (content, url) { };
/**
* @abstract
* @param {?} message
* @return {?}
*/
Serializer.prototype.digest = function (message) { };
/**
* @param {?} message
* @return {?}
*/
Serializer.prototype.createNameMapper = function (message) { return null; };
return Serializer;
}());
/**
* A simple mapper that take a function to transform an internal name to a public name
*/
var SimplePlaceholderMapper = (function (_super) {
__extends(SimplePlaceholderMapper, _super);
/**
* @param {?} message
* @param {?} mapName
*/
function SimplePlaceholderMapper(message, mapName) {
var _this = _super.call(this) || this;
_this.mapName = mapName;
_this.internalToPublic = {};
_this.publicToNextId = {};
_this.publicToInternal = {};
message.nodes.forEach(function (node) { return node.visit(_this); });
return _this;
}
/**
* @param {?} internalName
* @return {?}
*/
SimplePlaceholderMapper.prototype.toPublicName = function (internalName) {
return this.internalToPublic.hasOwnProperty(internalName) ?
this.internalToPublic[internalName] :
null;
};
/**
* @param {?} publicName
* @return {?}
*/
SimplePlaceholderMapper.prototype.toInternalName = function (publicName) {
return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
null;
};
/**
* @param {?} text
* @param {?=} context
* @return {?}
*/
SimplePlaceholderMapper.prototype.visitText = function (text, context) { return null; };
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) {
this.visitPlaceholderName(ph.startName);
_super.prototype.visitTagPlaceholder.call(this, ph, context);
this.visitPlaceholderName(ph.closeName);
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); };
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) {
this.visitPlaceholderName(ph.name);
};
/**
* @param {?} internalName
* @return {?}
*/
SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) {
if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
return;
}
var /** @type {?} */ publicName = this.mapName(internalName);
if (this.publicToInternal.hasOwnProperty(publicName)) {
// Create a new XMB when it has already been used
var /** @type {?} */ nextId = this.publicToNextId[publicName];
this.publicToNextId[publicName] = nextId + 1;
publicName = publicName + "_" + nextId;
}
else {
this.publicToNextId[publicName] = 1;
}
this.internalToPublic[internalName] = publicName;
this.publicToInternal[publicName] = internalName;
};
return SimplePlaceholderMapper;
}(RecurseVisitor));
/**
* @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
*/
var _Visitor$1 = (function () {
function _Visitor$1() {
}
/**
* @param {?} tag
* @return {?}
*/
_Visitor$1.prototype.visitTag = function (tag) {
var _this = this;
var /** @type {?} */ strAttrs = this._serializeAttributes(tag.attrs);
if (tag.children.length == 0) {
return "<" + tag.name + strAttrs + "/>";
}
var /** @type {?} */ strChildren = tag.children.map(function (node) { return node.visit(_this); });
return "<" + tag.name + strAttrs + ">" + strChildren.join('') + "</" + tag.name + ">";
};
/**
* @param {?} text
* @return {?}
*/
_Visitor$1.prototype.visitText = function (text) { return text.value; };
/**
* @param {?} decl
* @return {?}
*/
_Visitor$1.prototype.visitDeclaration = function (decl) {
return "<?xml" + this._serializeAttributes(decl.attrs) + " ?>";
};
/**
* @param {?} attrs
* @return {?}
*/
_Visitor$1.prototype._serializeAttributes = function (attrs) {
var /** @type {?} */ strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' ');
return strAttrs.length > 0 ? ' ' + strAttrs : '';
};
/**
* @param {?} doctype
* @return {?}
*/
_Visitor$1.prototype.visitDoctype = function (doctype) {
return "<!DOCTYPE " + doctype.rootTag + " [\n" + doctype.dtd + "\n]>";
};
return _Visitor$1;
}());
var _visitor = new _Visitor$1();
/**
* @param {?} nodes
* @return {?}
*/
function serialize(nodes) {
return nodes.map(function (node) { return node.visit(_visitor); }).join('');
}
var Declaration = (function () {
/**
* @param {?} unescapedAttrs
*/
function Declaration(unescapedAttrs) {
var _this = this;
this.attrs = {};
Object.keys(unescapedAttrs).forEach(function (k) {
_this.attrs[k] = _escapeXml(unescapedAttrs[k]);
});
}
/**
* @param {?} visitor
* @return {?}
*/
Declaration.prototype.visit = function (visitor) { return visitor.visitDeclaration(this); };
return Declaration;
}());
var Doctype = (function () {
/**
* @param {?} rootTag
* @param {?} dtd
*/
function Doctype(rootTag, dtd) {
this.rootTag = rootTag;
this.dtd = dtd;
}
;
/**
* @param {?} visitor
* @return {?}
*/
Doctype.prototype.visit = function (visitor) { return visitor.visitDoctype(this); };
return Doctype;
}());
var Tag = (function () {
/**
* @param {?} name
* @param {?=} unescapedAttrs
* @param {?=} children
*/
function Tag(name, unescapedAttrs, children) {
if (unescapedAttrs === void 0) { unescapedAttrs = {}; }
if (children === void 0) { children = []; }
var _this = this;
this.name = name;
this.children = children;
this.attrs = {};
Object.keys(unescapedAttrs).forEach(function (k) {
_this.attrs[k] = _escapeXml(unescapedAttrs[k]);
});
}
/**
* @param {?} visitor
* @return {?}
*/
Tag.prototype.visit = function (visitor) { return visitor.visitTag(this); };
return Tag;
}());
var Text$2 = (function () {
/**
* @param {?} unescapedValue
*/
function Text$2(unescapedValue) {
this.value = _escapeXml(unescapedValue);
}
;
/**
* @param {?} visitor
* @return {?}
*/
Text$2.prototype.visit = function (visitor) { return visitor.visitText(this); };
return Text$2;
}());
var CR = (function (_super) {
__extends(CR, _super);
/**
* @param {?=} ws
*/
function CR(ws) {
if (ws === void 0) { ws = 0; }
return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this;
}
return CR;
}(Text$2));
var _ESCAPED_CHARS = [
[/&/g, '&amp;'],
[/"/g, '&quot;'],
[/'/g, '&apos;'],
[/</g, '&lt;'],
[/>/g, '&gt;'],
];
/**
* @param {?} text
* @return {?}
*/
function _escapeXml(text) {
return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text);
}
/**
* @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
*/
var _VERSION = '1.2';
var _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
// TODO(vicb): make this a param (s/_/-/)
var _DEFAULT_SOURCE_LANG = 'en';
var _PLACEHOLDER_TAG = 'x';
var _FILE_TAG = 'file';
var _SOURCE_TAG = 'source';
var _TARGET_TAG = 'target';
var _UNIT_TAG = 'trans-unit';
var _CONTEXT_GROUP_TAG = 'context-group';
var _CONTEXT_TAG = 'context';
var Xliff = (function (_super) {
__extends(Xliff, _super);
function Xliff() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} messages
* @param {?} locale
* @return {?}
*/
Xliff.prototype.write = function (messages, locale) {
var /** @type {?} */ visitor = new _WriteVisitor();
var /** @type {?} */ transUnits = [];
messages.forEach(function (message) {
var /** @type {?} */ contextTags = [];
message.sources.forEach(function (source) {
var /** @type {?} */ contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: 'location' });
contextGroupTag.children.push(new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'sourcefile' }, [new Text$2(source.filePath)]), new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'linenumber' }, [new Text$2("" + source.startLine)]), new CR(8));
contextTags.push(new CR(8), contextGroupTag);
});
var /** @type {?} */ transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
(_a = transUnit.children).push.apply(_a, [new CR(8), new Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)), new CR(8), new Tag(_TARGET_TAG)].concat(contextTags));
if (message.description) {
transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)]));
}
if (message.meaning) {
transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)]));
}
transUnit.children.push(new CR(6));
transUnits.push(new CR(6), transUnit);
var _a;
});
var /** @type {?} */ body = new Tag('body', {}, transUnits.concat([new CR(4)]));
var /** @type {?} */ file = new Tag('file', {
'source-language': locale || _DEFAULT_SOURCE_LANG,
datatype: 'plaintext',
original: 'ng2.template',
}, [new CR(4), body, new CR(2)]);
var /** @type {?} */ xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]);
return serialize([
new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
]);
};
/**
* @param {?} content
* @param {?} url
* @return {?}
*/
Xliff.prototype.load = function (content, url) {
// xliff to xml nodes
var /** @type {?} */ xliffParser = new XliffParser();
var _a = xliffParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
// xml nodes to i18n nodes
var /** @type {?} */ i18nNodesByMsgId = {};
var /** @type {?} */ converter = new XmlToI18n();
Object.keys(msgIdToHtml).forEach(function (msgId) {
var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
errors.push.apply(errors, e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error("xliff parse errors:\n" + errors.join('\n'));
}
return { locale: /** @type {?} */ ((locale)), i18nNodesByMsgId: i18nNodesByMsgId };
};
/**
* @param {?} message
* @return {?}
*/
Xliff.prototype.digest = function (message) { return digest(message); };
return Xliff;
}(Serializer));
var _WriteVisitor = (function () {
function _WriteVisitor() {
}
/**
* @param {?} text
* @param {?=} context
* @return {?}
*/
_WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
/**
* @param {?} container
* @param {?=} context
* @return {?}
*/
_WriteVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
var /** @type {?} */ nodes = [];
container.children.forEach(function (node) { return nodes.push.apply(nodes, node.visit(_this)); });
return nodes;
};
/**
* @param {?} icu
* @param {?=} context
* @return {?}
*/
_WriteVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var /** @type {?} */ nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
Object.keys(icu.cases).forEach(function (c) {
nodes.push.apply(nodes, [new Text$2(c + " {")].concat(icu.cases[c].visit(_this), [new Text$2("} ")]));
});
nodes.push(new Text$2("}"));
return nodes;
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
var /** @type {?} */ ctype = getCtypeForTag(ph.tag);
var /** @type {?} */ startTagPh = new Tag(_PLACEHOLDER_TAG, { id: ph.startName, ctype: ctype });
if (ph.isVoid) {
// void tags have no children nor closing tags
return [startTagPh];
}
var /** @type {?} */ closeTagPh = new Tag(_PLACEHOLDER_TAG, { id: ph.closeName, ctype: ctype });
return [startTagPh].concat(this.serialize(ph.children), [closeTagPh]);
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
return [new Tag(_PLACEHOLDER_TAG, { id: ph.name })];
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
return [new Tag(_PLACEHOLDER_TAG, { id: ph.name })];
};
/**
* @param {?} nodes
* @return {?}
*/
_WriteVisitor.prototype.serialize = function (nodes) {
var _this = this;
return [].concat.apply([], nodes.map(function (node) { return node.visit(_this); }));
};
return _WriteVisitor;
}());
var XliffParser = (function () {
function XliffParser() {
this._locale = null;
}
/**
* @param {?} xliff
* @param {?} url
* @return {?}
*/
XliffParser.prototype.parse = function (xliff, url) {
this._unitMlString = null;
this._msgIdToHtml = {};
var /** @type {?} */ xml = new XmlParser().parse(xliff, url, false);
this._errors = xml.errors;
visitAll(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
};
/**
* @param {?} element
* @param {?} context
* @return {?}
*/
XliffParser.prototype.visitElement = function (element, context) {
switch (element.name) {
case _UNIT_TAG:
this._unitMlString = ((null));
var /** @type {?} */ idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!idAttr) {
this._addError(element, "<" + _UNIT_TAG + "> misses the \"id\" attribute");
}
else {
var /** @type {?} */ id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, "Duplicated translations for msg " + id);
}
else {
visitAll(this, element.children, null);
if (typeof this._unitMlString === 'string') {
this._msgIdToHtml[id] = this._unitMlString;
}
else {
this._addError(element, "Message " + id + " misses a translation");
}
}
}
break;
case _SOURCE_TAG:
// ignore source message
break;
case _TARGET_TAG:
var /** @type {?} */ innerTextStart = ((element.startSourceSpan)).end.offset;
var /** @type {?} */ innerTextEnd = ((element.endSourceSpan)).start.offset;
var /** @type {?} */ content = ((element.startSourceSpan)).start.file.content;
var /** @type {?} */ innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _FILE_TAG:
var /** @type {?} */ localeAttr = element.attrs.find(function (attr) { return attr.name === 'target-language'; });
if (localeAttr) {
this._locale = localeAttr.value;
}
visitAll(this, element.children, null);
break;
default:
// TODO(vicb): assert file structure, xliff version
// For now only recurse on unhandled nodes
visitAll(this, element.children, null);
}
};
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
XliffParser.prototype.visitAttribute = function (attribute, context) { };
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
XliffParser.prototype.visitText = function (text, context) { };
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
XliffParser.prototype.visitComment = function (comment, context) { };
/**
* @param {?} expansion
* @param {?} context
* @return {?}
*/
XliffParser.prototype.visitExpansion = function (expansion, context) { };
/**
* @param {?} expansionCase
* @param {?} context
* @return {?}
*/
XliffParser.prototype.visitExpansionCase = function (expansionCase, context) { };
/**
* @param {?} node
* @param {?} message
* @return {?}
*/
XliffParser.prototype._addError = function (node, message) {
this._errors.push(new I18nError(/** @type {?} */ ((node.sourceSpan)), message));
};
return XliffParser;
}());
var XmlToI18n = (function () {
function XmlToI18n() {
}
/**
* @param {?} message
* @param {?} url
* @return {?}
*/
XmlToI18n.prototype.convert = function (message, url) {
var /** @type {?} */ xmlIcu = new XmlParser().parse(message, url, true);
this._errors = xmlIcu.errors;
var /** @type {?} */ i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] :
visitAll(this, xmlIcu.rootNodes);
return {
i18nNodes: i18nNodes,
errors: this._errors,
};
};
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, /** @type {?} */ ((text.sourceSpan))); };
/**
* @param {?} el
* @param {?} context
* @return {?}
*/
XmlToI18n.prototype.visitElement = function (el, context) {
if (el.name === _PLACEHOLDER_TAG) {
var /** @type {?} */ nameAttr = el.attrs.find(function (attr) { return attr.name === 'id'; });
if (nameAttr) {
return new Placeholder('', nameAttr.value, /** @type {?} */ ((el.sourceSpan)));
}
this._addError(el, "<" + _PLACEHOLDER_TAG + "> misses the \"id\" attribute");
}
else {
this._addError(el, "Unexpected tag");
}
return null;
};
/**
* @param {?} icu
* @param {?} context
* @return {?}
*/
XmlToI18n.prototype.visitExpansion = function (icu, context) {
var /** @type {?} */ caseMap = {};
visitAll(this, icu.cases).forEach(function (c) {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
};
/**
* @param {?} icuCase
* @param {?} context
* @return {?}
*/
XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
return {
value: icuCase.value,
nodes: visitAll(this, icuCase.expression),
};
};
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
XmlToI18n.prototype.visitComment = function (comment, context) { };
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
/**
* @param {?} node
* @param {?} message
* @return {?}
*/
XmlToI18n.prototype._addError = function (node, message) {
this._errors.push(new I18nError(/** @type {?} */ ((node.sourceSpan)), message));
};
return XmlToI18n;
}());
/**
* @param {?} tag
* @return {?}
*/
function getCtypeForTag(tag) {
switch (tag.toLowerCase()) {
case 'br':
return 'lb';
case 'img':
return 'image';
default:
return "x-" + tag;
}
}
/**
* @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
*/
var _VERSION$1 = '2.0';
var _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
// TODO(vicb): make this a param (s/_/-/)
var _DEFAULT_SOURCE_LANG$1 = 'en';
var _PLACEHOLDER_TAG$1 = 'ph';
var _PLACEHOLDER_SPANNING_TAG = 'pc';
var _XLIFF_TAG = 'xliff';
var _SOURCE_TAG$1 = 'source';
var _TARGET_TAG$1 = 'target';
var _UNIT_TAG$1 = 'unit';
var Xliff2 = (function (_super) {
__extends(Xliff2, _super);
function Xliff2() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} messages
* @param {?} locale
* @return {?}
*/
Xliff2.prototype.write = function (messages, locale) {
var /** @type {?} */ visitor = new _WriteVisitor$1();
var /** @type {?} */ units = [];
messages.forEach(function (message) {
var /** @type {?} */ unit = new Tag(_UNIT_TAG$1, { id: message.id });
if (message.description || message.meaning) {
var /** @type {?} */ notes = new Tag('notes');
if (message.description) {
notes.children.push(new CR(8), new Tag('note', { category: 'description' }, [new Text$2(message.description)]));
}
if (message.meaning) {
notes.children.push(new CR(8), new Tag('note', { category: 'meaning' }, [new Text$2(message.meaning)]));
}
notes.children.push(new CR(6));
unit.children.push(new CR(6), notes);
}
var /** @type {?} */ segment = new Tag('segment');
segment.children.push(new CR(8), new Tag(_SOURCE_TAG$1, {}, visitor.serialize(message.nodes)), new CR(6));
unit.children.push(new CR(6), segment, new CR(4));
units.push(new CR(4), unit);
});
var /** @type {?} */ file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, units.concat([new CR(2)]));
var /** @type {?} */ xliff = new Tag(_XLIFF_TAG, { version: _VERSION$1, xmlns: _XMLNS$1, srcLang: locale || _DEFAULT_SOURCE_LANG$1 }, [new CR(2), file, new CR()]);
return serialize([
new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
]);
};
/**
* @param {?} content
* @param {?} url
* @return {?}
*/
Xliff2.prototype.load = function (content, url) {
// xliff to xml nodes
var /** @type {?} */ xliff2Parser = new Xliff2Parser();
var _a = xliff2Parser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
// xml nodes to i18n nodes
var /** @type {?} */ i18nNodesByMsgId = {};
var /** @type {?} */ converter = new XmlToI18n$1();
Object.keys(msgIdToHtml).forEach(function (msgId) {
var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
errors.push.apply(errors, e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error("xliff2 parse errors:\n" + errors.join('\n'));
}
return { locale: /** @type {?} */ ((locale)), i18nNodesByMsgId: i18nNodesByMsgId };
};
/**
* @param {?} message
* @return {?}
*/
Xliff2.prototype.digest = function (message) { return decimalDigest(message); };
return Xliff2;
}(Serializer));
var _WriteVisitor$1 = (function () {
function _WriteVisitor$1() {
}
/**
* @param {?} text
* @param {?=} context
* @return {?}
*/
_WriteVisitor$1.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
/**
* @param {?} container
* @param {?=} context
* @return {?}
*/
_WriteVisitor$1.prototype.visitContainer = function (container, context) {
var _this = this;
var /** @type {?} */ nodes = [];
container.children.forEach(function (node) { return nodes.push.apply(nodes, node.visit(_this)); });
return nodes;
};
/**
* @param {?} icu
* @param {?=} context
* @return {?}
*/
_WriteVisitor$1.prototype.visitIcu = function (icu, context) {
var _this = this;
var /** @type {?} */ nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
Object.keys(icu.cases).forEach(function (c) {
nodes.push.apply(nodes, [new Text$2(c + " {")].concat(icu.cases[c].visit(_this), [new Text$2("} ")]));
});
nodes.push(new Text$2("}"));
return nodes;
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_WriteVisitor$1.prototype.visitTagPlaceholder = function (ph, context) {
var _this = this;
var /** @type {?} */ type = getTypeForTag(ph.tag);
if (ph.isVoid) {
var /** @type {?} */ tagPh = new Tag(_PLACEHOLDER_TAG$1, {
id: (this._nextPlaceholderId++).toString(),
equiv: ph.startName,
type: type,
disp: "<" + ph.tag + "/>",
});
return [tagPh];
}
var /** @type {?} */ tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
id: (this._nextPlaceholderId++).toString(),
equivStart: ph.startName,
equivEnd: ph.closeName,
type: type,
dispStart: "<" + ph.tag + ">",
dispEnd: "</" + ph.tag + ">",
});
var /** @type {?} */ nodes = [].concat.apply([], ph.children.map(function (node) { return node.visit(_this); }));
if (nodes.length) {
nodes.forEach(function (node) { return tagPc.children.push(node); });
}
else {
tagPc.children.push(new Text$2(''));
}
return [tagPc];
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_WriteVisitor$1.prototype.visitPlaceholder = function (ph, context) {
return [new Tag(_PLACEHOLDER_TAG$1, {
id: (this._nextPlaceholderId++).toString(),
equiv: ph.name,
disp: "{{" + ph.value + "}}",
})];
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_WriteVisitor$1.prototype.visitIcuPlaceholder = function (ph, context) {
return [new Tag(_PLACEHOLDER_TAG$1, { id: (this._nextPlaceholderId++).toString() })];
};
/**
* @param {?} nodes
* @return {?}
*/
_WriteVisitor$1.prototype.serialize = function (nodes) {
var _this = this;
this._nextPlaceholderId = 0;
return [].concat.apply([], nodes.map(function (node) { return node.visit(_this); }));
};
return _WriteVisitor$1;
}());
var Xliff2Parser = (function () {
function Xliff2Parser() {
this._locale = null;
}
/**
* @param {?} xliff
* @param {?} url
* @return {?}
*/
Xliff2Parser.prototype.parse = function (xliff, url) {
this._unitMlString = null;
this._msgIdToHtml = {};
var /** @type {?} */ xml = new XmlParser().parse(xliff, url, false);
this._errors = xml.errors;
visitAll(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
};
/**
* @param {?} element
* @param {?} context
* @return {?}
*/
Xliff2Parser.prototype.visitElement = function (element, context) {
switch (element.name) {
case _UNIT_TAG$1:
this._unitMlString = null;
var /** @type {?} */ idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!idAttr) {
this._addError(element, "<" + _UNIT_TAG$1 + "> misses the \"id\" attribute");
}
else {
var /** @type {?} */ id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, "Duplicated translations for msg " + id);
}
else {
visitAll(this, element.children, null);
if (typeof this._unitMlString === 'string') {
this._msgIdToHtml[id] = this._unitMlString;
}
else {
this._addError(element, "Message " + id + " misses a translation");
}
}
}
break;
case _SOURCE_TAG$1:
// ignore source message
break;
case _TARGET_TAG$1:
var /** @type {?} */ innerTextStart = ((element.startSourceSpan)).end.offset;
var /** @type {?} */ innerTextEnd = ((element.endSourceSpan)).start.offset;
var /** @type {?} */ content = ((element.startSourceSpan)).start.file.content;
var /** @type {?} */ innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _XLIFF_TAG:
var /** @type {?} */ localeAttr = element.attrs.find(function (attr) { return attr.name === 'trgLang'; });
if (localeAttr) {
this._locale = localeAttr.value;
}
var /** @type {?} */ versionAttr = element.attrs.find(function (attr) { return attr.name === 'version'; });
if (versionAttr) {
var /** @type {?} */ version = versionAttr.value;
if (version !== '2.0') {
this._addError(element, "The XLIFF file version " + version + " is not compatible with XLIFF 2.0 serializer");
}
else {
visitAll(this, element.children, null);
}
}
break;
default:
visitAll(this, element.children, null);
}
};
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
Xliff2Parser.prototype.visitAttribute = function (attribute, context) { };
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
Xliff2Parser.prototype.visitText = function (text, context) { };
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
Xliff2Parser.prototype.visitComment = function (comment, context) { };
/**
* @param {?} expansion
* @param {?} context
* @return {?}
*/
Xliff2Parser.prototype.visitExpansion = function (expansion, context) { };
/**
* @param {?} expansionCase
* @param {?} context
* @return {?}
*/
Xliff2Parser.prototype.visitExpansionCase = function (expansionCase, context) { };
/**
* @param {?} node
* @param {?} message
* @return {?}
*/
Xliff2Parser.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return Xliff2Parser;
}());
var XmlToI18n$1 = (function () {
function XmlToI18n$1() {
}
/**
* @param {?} message
* @param {?} url
* @return {?}
*/
XmlToI18n$1.prototype.convert = function (message, url) {
var /** @type {?} */ xmlIcu = new XmlParser().parse(message, url, true);
this._errors = xmlIcu.errors;
var /** @type {?} */ i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] : [].concat.apply([], visitAll(this, xmlIcu.rootNodes));
return {
i18nNodes: i18nNodes,
errors: this._errors,
};
};
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
XmlToI18n$1.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
/**
* @param {?} el
* @param {?} context
* @return {?}
*/
XmlToI18n$1.prototype.visitElement = function (el, context) {
var _this = this;
switch (el.name) {
case _PLACEHOLDER_TAG$1:
var /** @type {?} */ nameAttr = el.attrs.find(function (attr) { return attr.name === 'equiv'; });
if (nameAttr) {
return [new Placeholder('', nameAttr.value, el.sourceSpan)];
}
this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"equiv\" attribute");
break;
case _PLACEHOLDER_SPANNING_TAG:
var /** @type {?} */ startAttr = el.attrs.find(function (attr) { return attr.name === 'equivStart'; });
var /** @type {?} */ endAttr = el.attrs.find(function (attr) { return attr.name === 'equivEnd'; });
if (!startAttr) {
this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"equivStart\" attribute");
}
else if (!endAttr) {
this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"equivEnd\" attribute");
}
else {
var /** @type {?} */ startId = startAttr.value;
var /** @type {?} */ endId = endAttr.value;
var /** @type {?} */ nodes = [];
return nodes.concat.apply(nodes, [new Placeholder('', startId, el.sourceSpan)].concat(el.children.map(function (node) { return node.visit(_this, null); }), [new Placeholder('', endId, el.sourceSpan)]));
}
break;
default:
this._addError(el, "Unexpected tag");
}
return null;
};
/**
* @param {?} icu
* @param {?} context
* @return {?}
*/
XmlToI18n$1.prototype.visitExpansion = function (icu, context) {
var /** @type {?} */ caseMap = {};
visitAll(this, icu.cases).forEach(function (c) {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
};
/**
* @param {?} icuCase
* @param {?} context
* @return {?}
*/
XmlToI18n$1.prototype.visitExpansionCase = function (icuCase, context) {
return {
value: icuCase.value,
nodes: [].concat.apply([], visitAll(this, icuCase.expression)),
};
};
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
XmlToI18n$1.prototype.visitComment = function (comment, context) { };
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
XmlToI18n$1.prototype.visitAttribute = function (attribute, context) { };
/**
* @param {?} node
* @param {?} message
* @return {?}
*/
XmlToI18n$1.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return XmlToI18n$1;
}());
/**
* @param {?} tag
* @return {?}
*/
function getTypeForTag(tag) {
switch (tag.toLowerCase()) {
case 'br':
case 'b':
case 'i':
case 'u':
return 'fmt';
case 'img':
return 'image';
case 'a':
return 'link';
default:
return 'other';
}
}
/**
* @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
*/
var _MESSAGES_TAG = 'messagebundle';
var _MESSAGE_TAG = 'msg';
var _PLACEHOLDER_TAG$2 = 'ph';
var _EXEMPLE_TAG = 'ex';
var _SOURCE_TAG$2 = 'source';
var _DOCTYPE = "<!ELEMENT messagebundle (msg)*>\n<!ATTLIST messagebundle class CDATA #IMPLIED>\n\n<!ELEMENT msg (#PCDATA|ph|source)*>\n<!ATTLIST msg id CDATA #IMPLIED>\n<!ATTLIST msg seq CDATA #IMPLIED>\n<!ATTLIST msg name CDATA #IMPLIED>\n<!ATTLIST msg desc CDATA #IMPLIED>\n<!ATTLIST msg meaning CDATA #IMPLIED>\n<!ATTLIST msg obsolete (obsolete) #IMPLIED>\n<!ATTLIST msg xml:space (default|preserve) \"default\">\n<!ATTLIST msg is_hidden CDATA #IMPLIED>\n\n<!ELEMENT source (#PCDATA)>\n\n<!ELEMENT ph (#PCDATA|ex)*>\n<!ATTLIST ph name CDATA #REQUIRED>\n\n<!ELEMENT ex (#PCDATA)>";
var Xmb = (function (_super) {
__extends(Xmb, _super);
function Xmb() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} messages
* @param {?} locale
* @return {?}
*/
Xmb.prototype.write = function (messages, locale) {
var /** @type {?} */ exampleVisitor = new ExampleVisitor();
var /** @type {?} */ visitor = new _Visitor$2();
var /** @type {?} */ rootNode = new Tag(_MESSAGES_TAG);
messages.forEach(function (message) {
var /** @type {?} */ attrs = { id: message.id };
if (message.description) {
attrs['desc'] = message.description;
}
if (message.meaning) {
attrs['meaning'] = message.meaning;
}
var /** @type {?} */ sourceTags = [];
message.sources.forEach(function (source) {
sourceTags.push(new Tag(_SOURCE_TAG$2, {}, [
new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
]));
});
rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, sourceTags.concat(visitor.serialize(message.nodes))));
});
rootNode.children.push(new CR());
return serialize([
new Declaration({ version: '1.0', encoding: 'UTF-8' }),
new CR(),
new Doctype(_MESSAGES_TAG, _DOCTYPE),
new CR(),
exampleVisitor.addDefaultExamples(rootNode),
new CR(),
]);
};
/**
* @param {?} content
* @param {?} url
* @return {?}
*/
Xmb.prototype.load = function (content, url) {
throw new Error('Unsupported');
};
/**
* @param {?} message
* @return {?}
*/
Xmb.prototype.digest = function (message) { return digest$1(message); };
/**
* @param {?} message
* @return {?}
*/
Xmb.prototype.createNameMapper = function (message) {
return new SimplePlaceholderMapper(message, toPublicName);
};
return Xmb;
}(Serializer));
var _Visitor$2 = (function () {
function _Visitor$2() {
}
/**
* @param {?} text
* @param {?=} context
* @return {?}
*/
_Visitor$2.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
/**
* @param {?} container
* @param {?} context
* @return {?}
*/
_Visitor$2.prototype.visitContainer = function (container, context) {
var _this = this;
var /** @type {?} */ nodes = [];
container.children.forEach(function (node) { return nodes.push.apply(nodes, node.visit(_this)); });
return nodes;
};
/**
* @param {?} icu
* @param {?=} context
* @return {?}
*/
_Visitor$2.prototype.visitIcu = function (icu, context) {
var _this = this;
var /** @type {?} */ nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
Object.keys(icu.cases).forEach(function (c) {
nodes.push.apply(nodes, [new Text$2(c + " {")].concat(icu.cases[c].visit(_this), [new Text$2("} ")]));
});
nodes.push(new Text$2("}"));
return nodes;
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_Visitor$2.prototype.visitTagPlaceholder = function (ph, context) {
var /** @type {?} */ startEx = new Tag(_EXEMPLE_TAG, {}, [new Text$2("<" + ph.tag + ">")]);
var /** @type {?} */ startTagPh = new Tag(_PLACEHOLDER_TAG$2, { name: ph.startName }, [startEx]);
if (ph.isVoid) {
// void tags have no children nor closing tags
return [startTagPh];
}
var /** @type {?} */ closeEx = new Tag(_EXEMPLE_TAG, {}, [new Text$2("</" + ph.tag + ">")]);
var /** @type {?} */ closeTagPh = new Tag(_PLACEHOLDER_TAG$2, { name: ph.closeName }, [closeEx]);
return [startTagPh].concat(this.serialize(ph.children), [closeTagPh]);
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_Visitor$2.prototype.visitPlaceholder = function (ph, context) {
return [new Tag(_PLACEHOLDER_TAG$2, { name: ph.name })];
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
_Visitor$2.prototype.visitIcuPlaceholder = function (ph, context) {
return [new Tag(_PLACEHOLDER_TAG$2, { name: ph.name })];
};
/**
* @param {?} nodes
* @return {?}
*/
_Visitor$2.prototype.serialize = function (nodes) {
var _this = this;
return [].concat.apply([], nodes.map(function (node) { return node.visit(_this); }));
};
return _Visitor$2;
}());
/**
* @param {?} message
* @return {?}
*/
function digest$1(message) {
return decimalDigest(message);
}
var ExampleVisitor = (function () {
function ExampleVisitor() {
}
/**
* @param {?} node
* @return {?}
*/
ExampleVisitor.prototype.addDefaultExamples = function (node) {
node.visit(this);
return node;
};
/**
* @param {?} tag
* @return {?}
*/
ExampleVisitor.prototype.visitTag = function (tag) {
var _this = this;
if (tag.name === _PLACEHOLDER_TAG$2) {
if (!tag.children || tag.children.length == 0) {
var /** @type {?} */ exText = new Text$2(tag.attrs['name'] || '...');
tag.children = [new Tag(_EXEMPLE_TAG, {}, [exText])];
}
}
else if (tag.children) {
tag.children.forEach(function (node) { return node.visit(_this); });
}
};
/**
* @param {?} text
* @return {?}
*/
ExampleVisitor.prototype.visitText = function (text) { };
/**
* @param {?} decl
* @return {?}
*/
ExampleVisitor.prototype.visitDeclaration = function (decl) { };
/**
* @param {?} doctype
* @return {?}
*/
ExampleVisitor.prototype.visitDoctype = function (doctype) { };
return ExampleVisitor;
}());
/**
* @param {?} internalName
* @return {?}
*/
function toPublicName(internalName) {
return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
}
/**
* @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
*/
var _TRANSLATIONS_TAG = 'translationbundle';
var _TRANSLATION_TAG = 'translation';
var _PLACEHOLDER_TAG$3 = 'ph';
var Xtb = (function (_super) {
__extends(Xtb, _super);
function Xtb() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} messages
* @param {?} locale
* @return {?}
*/
Xtb.prototype.write = function (messages, locale) { throw new Error('Unsupported'); };
/**
* @param {?} content
* @param {?} url
* @return {?}
*/
Xtb.prototype.load = function (content, url) {
// xtb to xml nodes
var /** @type {?} */ xtbParser = new XtbParser();
var _a = xtbParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
// xml nodes to i18n nodes
var /** @type {?} */ i18nNodesByMsgId = {};
var /** @type {?} */ converter = new XmlToI18n$2();
// Because we should be able to load xtb files that rely on features not supported by angular,
// we need to delay the conversion of html to i18n nodes so that non angular messages are not
// converted
Object.keys(msgIdToHtml).forEach(function (msgId) {
var /** @type {?} */ valueFn = function () {
var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, errors = _a.errors;
if (errors.length) {
throw new Error("xtb parse errors:\n" + errors.join('\n'));
}
return i18nNodes;
};
createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
});
if (errors.length) {
throw new Error("xtb parse errors:\n" + errors.join('\n'));
}
return { locale: /** @type {?} */ ((locale)), i18nNodesByMsgId: i18nNodesByMsgId };
};
/**
* @param {?} message
* @return {?}
*/
Xtb.prototype.digest = function (message) { return digest$1(message); };
/**
* @param {?} message
* @return {?}
*/
Xtb.prototype.createNameMapper = function (message) {
return new SimplePlaceholderMapper(message, toPublicName);
};
return Xtb;
}(Serializer));
/**
* @param {?} messages
* @param {?} id
* @param {?} valueFn
* @return {?}
*/
function createLazyProperty(messages, id, valueFn) {
Object.defineProperty(messages, id, {
configurable: true,
enumerable: true,
get: function () {
var /** @type {?} */ value = valueFn();
Object.defineProperty(messages, id, { enumerable: true, value: value });
return value;
},
set: function (_) { throw new Error('Could not overwrite an XTB translation'); },
});
}
var XtbParser = (function () {
function XtbParser() {
this._locale = null;
}
/**
* @param {?} xtb
* @param {?} url
* @return {?}
*/
XtbParser.prototype.parse = function (xtb, url) {
this._bundleDepth = 0;
this._msgIdToHtml = {};
// We can not parse the ICU messages at this point as some messages might not originate
// from Angular that could not be lex'd.
var /** @type {?} */ xml = new XmlParser().parse(xtb, url, false);
this._errors = xml.errors;
visitAll(this, xml.rootNodes);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
};
/**
* @param {?} element
* @param {?} context
* @return {?}
*/
XtbParser.prototype.visitElement = function (element, context) {
switch (element.name) {
case _TRANSLATIONS_TAG:
this._bundleDepth++;
if (this._bundleDepth > 1) {
this._addError(element, "<" + _TRANSLATIONS_TAG + "> elements can not be nested");
}
var /** @type {?} */ langAttr = element.attrs.find(function (attr) { return attr.name === 'lang'; });
if (langAttr) {
this._locale = langAttr.value;
}
visitAll(this, element.children, null);
this._bundleDepth--;
break;
case _TRANSLATION_TAG:
var /** @type {?} */ idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!idAttr) {
this._addError(element, "<" + _TRANSLATION_TAG + "> misses the \"id\" attribute");
}
else {
var /** @type {?} */ id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, "Duplicated translations for msg " + id);
}
else {
var /** @type {?} */ innerTextStart = ((element.startSourceSpan)).end.offset;
var /** @type {?} */ innerTextEnd = ((element.endSourceSpan)).start.offset;
var /** @type {?} */ content = ((element.startSourceSpan)).start.file.content;
var /** @type {?} */ innerText = content.slice(/** @type {?} */ ((innerTextStart)), /** @type {?} */ ((innerTextEnd)));
this._msgIdToHtml[id] = innerText;
}
}
break;
default:
this._addError(element, 'Unexpected tag');
}
};
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
XtbParser.prototype.visitAttribute = function (attribute, context) { };
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
XtbParser.prototype.visitText = function (text, context) { };
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
XtbParser.prototype.visitComment = function (comment, context) { };
/**
* @param {?} expansion
* @param {?} context
* @return {?}
*/
XtbParser.prototype.visitExpansion = function (expansion, context) { };
/**
* @param {?} expansionCase
* @param {?} context
* @return {?}
*/
XtbParser.prototype.visitExpansionCase = function (expansionCase, context) { };
/**
* @param {?} node
* @param {?} message
* @return {?}
*/
XtbParser.prototype._addError = function (node, message) {
this._errors.push(new I18nError(/** @type {?} */ ((node.sourceSpan)), message));
};
return XtbParser;
}());
var XmlToI18n$2 = (function () {
function XmlToI18n$2() {
}
/**
* @param {?} message
* @param {?} url
* @return {?}
*/
XmlToI18n$2.prototype.convert = function (message, url) {
var /** @type {?} */ xmlIcu = new XmlParser().parse(message, url, true);
this._errors = xmlIcu.errors;
var /** @type {?} */ i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] :
visitAll(this, xmlIcu.rootNodes);
return {
i18nNodes: i18nNodes,
errors: this._errors,
};
};
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
XmlToI18n$2.prototype.visitText = function (text, context) { return new Text$1(text.value, /** @type {?} */ ((text.sourceSpan))); };
/**
* @param {?} icu
* @param {?} context
* @return {?}
*/
XmlToI18n$2.prototype.visitExpansion = function (icu, context) {
var /** @type {?} */ caseMap = {};
visitAll(this, icu.cases).forEach(function (c) {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
};
/**
* @param {?} icuCase
* @param {?} context
* @return {?}
*/
XmlToI18n$2.prototype.visitExpansionCase = function (icuCase, context) {
return {
value: icuCase.value,
nodes: visitAll(this, icuCase.expression),
};
};
/**
* @param {?} el
* @param {?} context
* @return {?}
*/
XmlToI18n$2.prototype.visitElement = function (el, context) {
if (el.name === _PLACEHOLDER_TAG$3) {
var /** @type {?} */ nameAttr = el.attrs.find(function (attr) { return attr.name === 'name'; });
if (nameAttr) {
return new Placeholder('', nameAttr.value, /** @type {?} */ ((el.sourceSpan)));
}
this._addError(el, "<" + _PLACEHOLDER_TAG$3 + "> misses the \"name\" attribute");
}
else {
this._addError(el, "Unexpected tag");
}
return null;
};
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
XmlToI18n$2.prototype.visitComment = function (comment, context) { };
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
XmlToI18n$2.prototype.visitAttribute = function (attribute, context) { };
/**
* @param {?} node
* @param {?} message
* @return {?}
*/
XmlToI18n$2.prototype._addError = function (node, message) {
this._errors.push(new I18nError(/** @type {?} */ ((node.sourceSpan)), message));
};
return XmlToI18n$2;
}());
/**
* @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
*/
var HtmlParser = (function (_super) {
__extends(HtmlParser, _super);
function HtmlParser() {
return _super.call(this, getHtmlTagDefinition) || this;
}
/**
* @param {?} source
* @param {?} url
* @param {?=} parseExpansionForms
* @param {?=} interpolationConfig
* @return {?}
*/
HtmlParser.prototype.parse = function (source, url, parseExpansionForms, interpolationConfig) {
if (parseExpansionForms === void 0) { parseExpansionForms = false; }
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
return _super.prototype.parse.call(this, source, url, parseExpansionForms, interpolationConfig);
};
return HtmlParser;
}(Parser$1));
HtmlParser.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
HtmlParser.ctorParameters = function () { return []; };
/**
* @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
*/
/**
* A container for translated messages
*/
var TranslationBundle = (function () {
/**
* @param {?=} _i18nNodesByMsgId
* @param {?=} locale
* @param {?=} digest
* @param {?=} mapperFactory
* @param {?=} missingTranslationStrategy
* @param {?=} console
*/
function TranslationBundle(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console) {
if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
if (missingTranslationStrategy === void 0) { missingTranslationStrategy = __WEBPACK_IMPORTED_MODULE_0__angular_core__["_19" /* MissingTranslationStrategy */].Warning; }
this._i18nNodesByMsgId = _i18nNodesByMsgId;
this.digest = digest;
this.mapperFactory = mapperFactory;
this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console);
}
/**
* @param {?} content
* @param {?} url
* @param {?} serializer
* @param {?} missingTranslationStrategy
* @param {?=} console
* @return {?}
*/
TranslationBundle.load = function (content, url, serializer, missingTranslationStrategy, console) {
var _a = serializer.load(content, url), locale = _a.locale, i18nNodesByMsgId = _a.i18nNodesByMsgId;
var /** @type {?} */ digestFn = function (m) { return serializer.digest(m); };
var /** @type {?} */ mapperFactory = function (m) { return ((serializer.createNameMapper(m))); };
return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
};
/**
* @param {?} srcMsg
* @return {?}
*/
TranslationBundle.prototype.get = function (srcMsg) {
var /** @type {?} */ html = this._i18nToHtml.convert(srcMsg);
if (html.errors.length) {
throw new Error(html.errors.join('\n'));
}
return html.nodes;
};
/**
* @param {?} srcMsg
* @return {?}
*/
TranslationBundle.prototype.has = function (srcMsg) { return this.digest(srcMsg) in this._i18nNodesByMsgId; };
return TranslationBundle;
}());
var I18nToHtmlVisitor = (function () {
/**
* @param {?=} _i18nNodesByMsgId
* @param {?=} _locale
* @param {?=} _digest
* @param {?=} _mapperFactory
* @param {?=} _missingTranslationStrategy
* @param {?=} _console
*/
function I18nToHtmlVisitor(_i18nNodesByMsgId, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
this._i18nNodesByMsgId = _i18nNodesByMsgId;
this._locale = _locale;
this._digest = _digest;
this._mapperFactory = _mapperFactory;
this._missingTranslationStrategy = _missingTranslationStrategy;
this._console = _console;
this._contextStack = [];
this._errors = [];
}
/**
* @param {?} srcMsg
* @return {?}
*/
I18nToHtmlVisitor.prototype.convert = function (srcMsg) {
this._contextStack.length = 0;
this._errors.length = 0;
// i18n to text
var /** @type {?} */ text = this._convertToText(srcMsg);
// text to html
var /** @type {?} */ url = srcMsg.nodes[0].sourceSpan.start.file.url;
var /** @type {?} */ html = new HtmlParser().parse(text, url, true);
return {
nodes: html.rootNodes,
errors: this._errors.concat(html.errors),
};
};
/**
* @param {?} text
* @param {?=} context
* @return {?}
*/
I18nToHtmlVisitor.prototype.visitText = function (text, context) { return text.value; };
/**
* @param {?} container
* @param {?=} context
* @return {?}
*/
I18nToHtmlVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
return container.children.map(function (n) { return n.visit(_this); }).join('');
};
/**
* @param {?} icu
* @param {?=} context
* @return {?}
*/
I18nToHtmlVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var /** @type {?} */ cases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
// TODO(vicb): Once all format switch to using expression placeholders
// we should throw when the placeholder is not in the source message
var /** @type {?} */ exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
this._srcMsg.placeholders[icu.expression] :
icu.expression;
return "{" + exp + ", " + icu.type + ", " + cases.join(' ') + "}";
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
I18nToHtmlVisitor.prototype.visitPlaceholder = function (ph, context) {
var /** @type {?} */ phName = this._mapper(ph.name);
if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
return this._srcMsg.placeholders[phName];
}
if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
}
this._addError(ph, "Unknown placeholder \"" + ph.name + "\"");
return '';
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
I18nToHtmlVisitor.prototype.visitTagPlaceholder = function (ph, context) {
var _this = this;
var /** @type {?} */ tag = "" + ph.tag;
var /** @type {?} */ attrs = Object.keys(ph.attrs).map(function (name) { return name + "=\"" + ph.attrs[name] + "\""; }).join(' ');
if (ph.isVoid) {
return "<" + tag + " " + attrs + "/>";
}
var /** @type {?} */ children = ph.children.map(function (c) { return c.visit(_this); }).join('');
return "<" + tag + " " + attrs + ">" + children + "</" + tag + ">";
};
/**
* @param {?} ph
* @param {?=} context
* @return {?}
*/
I18nToHtmlVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
// An ICU placeholder references the source message to be serialized
return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
};
/**
* Convert a source message to a translated text string:
* - text nodes are replaced with their translation,
* - placeholders are replaced with their content,
* - ICU nodes are converted to ICU expressions.
* @param {?} srcMsg
* @return {?}
*/
I18nToHtmlVisitor.prototype._convertToText = function (srcMsg) {
var _this = this;
var /** @type {?} */ id = this._digest(srcMsg);
var /** @type {?} */ mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
var /** @type {?} */ nodes;
this._contextStack.push({ msg: this._srcMsg, mapper: this._mapper });
this._srcMsg = srcMsg;
if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
// When there is a translation use its nodes as the source
// And create a mapper to convert serialized placeholder names to internal names
nodes = this._i18nNodesByMsgId[id];
this._mapper = function (name) { return mapper ? ((mapper.toInternalName(name))) : name; };
}
else {
// When no translation has been found
// - report an error / a warning / nothing,
// - use the nodes from the original message
// - placeholders are already internal and need no mapper
if (this._missingTranslationStrategy === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_19" /* MissingTranslationStrategy */].Error) {
var /** @type {?} */ ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
this._addError(srcMsg.nodes[0], "Missing translation for message \"" + id + "\"" + ctx);
}
else if (this._console &&
this._missingTranslationStrategy === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_19" /* MissingTranslationStrategy */].Warning) {
var /** @type {?} */ ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
this._console.warn("Missing translation for message \"" + id + "\"" + ctx);
}
nodes = srcMsg.nodes;
this._mapper = function (name) { return name; };
}
var /** @type {?} */ text = nodes.map(function (node) { return node.visit(_this); }).join('');
var /** @type {?} */ context = ((this._contextStack.pop()));
this._srcMsg = context.msg;
this._mapper = context.mapper;
return text;
};
/**
* @param {?} el
* @param {?} msg
* @return {?}
*/
I18nToHtmlVisitor.prototype._addError = function (el, msg) {
this._errors.push(new I18nError(el.sourceSpan, msg));
};
return I18nToHtmlVisitor;
}());
/**
* @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
*/
var I18NHtmlParser = (function () {
/**
* @param {?} _htmlParser
* @param {?=} translations
* @param {?=} translationsFormat
* @param {?=} missingTranslation
* @param {?=} console
*/
function I18NHtmlParser(_htmlParser, translations, translationsFormat, missingTranslation, console) {
if (missingTranslation === void 0) { missingTranslation = __WEBPACK_IMPORTED_MODULE_0__angular_core__["_19" /* MissingTranslationStrategy */].Warning; }
this._htmlParser = _htmlParser;
if (translations) {
var serializer = createSerializer(translationsFormat);
this._translationBundle =
TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
}
}
/**
* @param {?} source
* @param {?} url
* @param {?=} parseExpansionForms
* @param {?=} interpolationConfig
* @return {?}
*/
I18NHtmlParser.prototype.parse = function (source, url, parseExpansionForms, interpolationConfig) {
if (parseExpansionForms === void 0) { parseExpansionForms = false; }
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
var /** @type {?} */ parseResult = this._htmlParser.parse(source, url, parseExpansionForms, interpolationConfig);
if (!this._translationBundle) {
// Do not enable i18n when no translation bundle is provided
return parseResult;
}
if (parseResult.errors.length) {
return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
}
return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
};
return I18NHtmlParser;
}());
/**
* @param {?=} format
* @return {?}
*/
function createSerializer(format) {
format = (format || 'xlf').toLowerCase();
switch (format) {
case 'xmb':
return new Xmb();
case 'xtb':
return new Xtb();
case 'xliff2':
case 'xlf2':
return new Xliff2();
case 'xliff':
case 'xlf':
default:
return new Xliff();
}
}
/**
* @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
*/
var CORE = assetUrl('core');
var Identifiers = (function () {
function Identifiers() {
}
return Identifiers;
}());
Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS = {
name: 'ANALYZE_FOR_ENTRY_COMPONENTS',
moduleUrl: CORE,
runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_13" /* ANALYZE_FOR_ENTRY_COMPONENTS */]
};
Identifiers.ElementRef = { name: 'ElementRef', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["i" /* ElementRef */] };
Identifiers.NgModuleRef = { name: 'NgModuleRef', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["V" /* NgModuleRef */] };
Identifiers.ViewContainerRef = { name: 'ViewContainerRef', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["X" /* ViewContainerRef */] };
Identifiers.ChangeDetectorRef = { name: 'ChangeDetectorRef', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_2" /* ChangeDetectorRef */] };
Identifiers.QueryList = { name: 'QueryList', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_20" /* QueryList */] };
Identifiers.TemplateRef = { name: 'TemplateRef', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["Y" /* TemplateRef */] };
Identifiers.CodegenComponentFactoryResolver = {
name: 'ɵCodegenComponentFactoryResolver',
moduleUrl: CORE,
runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_21" /* ɵCodegenComponentFactoryResolver */]
};
Identifiers.ComponentFactoryResolver = {
name: 'ComponentFactoryResolver',
moduleUrl: CORE,
runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["W" /* ComponentFactoryResolver */]
};
Identifiers.ComponentFactory = { name: 'ComponentFactory', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_22" /* ComponentFactory */] };
Identifiers.ComponentRef = { name: 'ComponentRef', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_23" /* ComponentRef */] };
Identifiers.NgModuleFactory = { name: 'NgModuleFactory', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_5" /* NgModuleFactory */] };
Identifiers.NgModuleInjector = {
name: 'ɵNgModuleInjector',
moduleUrl: CORE,
runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_24" /* ɵNgModuleInjector */],
};
Identifiers.RegisterModuleFactoryFn = {
name: 'ɵregisterModuleFactory',
moduleUrl: CORE,
runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_25" /* ɵregisterModuleFactory */],
};
Identifiers.Injector = { name: 'Injector', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Injector */] };
Identifiers.ViewEncapsulation = { name: 'ViewEncapsulation', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */] };
Identifiers.ChangeDetectionStrategy = {
name: 'ChangeDetectionStrategy',
moduleUrl: CORE,
runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_4" /* ChangeDetectionStrategy */]
};
Identifiers.SecurityContext = {
name: 'SecurityContext',
moduleUrl: CORE,
runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */],
};
Identifiers.LOCALE_ID = { name: 'LOCALE_ID', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["Q" /* LOCALE_ID */] };
Identifiers.TRANSLATIONS_FORMAT = { name: 'TRANSLATIONS_FORMAT', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_26" /* TRANSLATIONS_FORMAT */] };
Identifiers.inlineInterpolate = { name: 'ɵinlineInterpolate', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_27" /* ɵinlineInterpolate */] };
Identifiers.interpolate = { name: 'ɵinterpolate', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_28" /* ɵinterpolate */] };
Identifiers.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_29" /* ɵEMPTY_ARRAY */] };
Identifiers.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_30" /* ɵEMPTY_MAP */] };
Identifiers.Renderer = { name: 'Renderer', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["h" /* Renderer */] };
Identifiers.viewDef = { name: 'ɵvid', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_31" /* ɵvid */] };
Identifiers.elementDef = { name: 'ɵeld', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_32" /* ɵeld */] };
Identifiers.anchorDef = { name: 'ɵand', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_33" /* ɵand */] };
Identifiers.textDef = { name: 'ɵted', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_34" /* ɵted */] };
Identifiers.directiveDef = { name: 'ɵdid', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_35" /* ɵdid */] };
Identifiers.providerDef = { name: 'ɵprd', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_36" /* ɵprd */] };
Identifiers.queryDef = { name: 'ɵqud', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_37" /* ɵqud */] };
Identifiers.pureArrayDef = { name: 'ɵpad', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_38" /* ɵpad */] };
Identifiers.pureObjectDef = { name: 'ɵpod', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_39" /* ɵpod */] };
Identifiers.purePipeDef = { name: 'ɵppd', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_40" /* ɵppd */] };
Identifiers.pipeDef = { name: 'ɵpid', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_41" /* ɵpid */] };
Identifiers.nodeValue = { name: 'ɵnov', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_42" /* ɵnov */] };
Identifiers.ngContentDef = { name: 'ɵncd', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_43" /* ɵncd */] };
Identifiers.unwrapValue = { name: 'ɵunv', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_44" /* ɵunv */] };
Identifiers.createRendererType2 = { name: 'ɵcrt', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_45" /* ɵcrt */] };
Identifiers.RendererType2 = {
name: 'RendererType2',
moduleUrl: CORE,
// type only
runtime: null
};
Identifiers.ViewDefinition = {
name: 'ɵViewDefinition',
moduleUrl: CORE,
// type only
runtime: null
};
Identifiers.createComponentFactory = { name: 'ɵccf', moduleUrl: CORE, runtime: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_46" /* ɵccf */] };
/**
* @param {?} pkg
* @param {?=} path
* @param {?=} type
* @return {?}
*/
function assetUrl(pkg, path, type) {
if (path === void 0) { path = null; }
if (type === void 0) { type = 'src'; }
if (path == null) {
return "@angular/" + pkg;
}
else {
return "@angular/" + pkg + "/" + type + "/" + path;
}
}
/**
* @param {?} identifier
* @return {?}
*/
function resolveIdentifier(identifier) {
var /** @type {?} */ name = identifier.name;
return __WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */].resolveIdentifier(name, identifier.moduleUrl, null, identifier.runtime);
}
/**
* @param {?} identifier
* @return {?}
*/
function createIdentifier(identifier) {
return { reference: resolveIdentifier(identifier) };
}
/**
* @param {?} identifier
* @return {?}
*/
function identifierToken(identifier) {
return { identifier: identifier };
}
/**
* @param {?} identifier
* @return {?}
*/
function createIdentifierToken(identifier) {
return identifierToken(createIdentifier(identifier));
}
/**
* @param {?} enumType
* @param {?} name
* @return {?}
*/
/**
* @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
*/
// http://cldr.unicode.org/index/cldr-spec/plural-rules
var PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other'];
/**
* Expands special forms into elements.
*
* For example,
*
* ```
* { messages.length, plural,
* =0 {zero}
* =1 {one}
* other {more than one}
* }
* ```
*
* will be expanded into
*
* ```
* <ng-container [ngPlural]="messages.length">
* <ng-template ngPluralCase="=0">zero</ng-template>
* <ng-template ngPluralCase="=1">one</ng-template>
* <ng-template ngPluralCase="other">more than one</ng-template>
* </ng-container>
* ```
* @param {?} nodes
* @return {?}
*/
function expandNodes(nodes) {
var /** @type {?} */ expander = new _Expander();
return new ExpansionResult(visitAll(expander, nodes), expander.isExpanded, expander.errors);
}
var ExpansionResult = (function () {
/**
* @param {?} nodes
* @param {?} expanded
* @param {?} errors
*/
function ExpansionResult(nodes, expanded, errors) {
this.nodes = nodes;
this.expanded = expanded;
this.errors = errors;
}
return ExpansionResult;
}());
var ExpansionError = (function (_super) {
__extends(ExpansionError, _super);
/**
* @param {?} span
* @param {?} errorMsg
*/
function ExpansionError(span, errorMsg) {
return _super.call(this, span, errorMsg) || this;
}
return ExpansionError;
}(ParseError));
/**
* Expand expansion forms (plural, select) to directives
*
* \@internal
*/
var _Expander = (function () {
function _Expander() {
this.isExpanded = false;
this.errors = [];
}
/**
* @param {?} element
* @param {?} context
* @return {?}
*/
_Expander.prototype.visitElement = function (element, context) {
return new Element(element.name, element.attrs, visitAll(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
};
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
_Expander.prototype.visitAttribute = function (attribute, context) { return attribute; };
/**
* @param {?} text
* @param {?} context
* @return {?}
*/
_Expander.prototype.visitText = function (text, context) { return text; };
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
_Expander.prototype.visitComment = function (comment, context) { return comment; };
/**
* @param {?} icu
* @param {?} context
* @return {?}
*/
_Expander.prototype.visitExpansion = function (icu, context) {
this.isExpanded = true;
return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) :
_expandDefaultForm(icu, this.errors);
};
/**
* @param {?} icuCase
* @param {?} context
* @return {?}
*/
_Expander.prototype.visitExpansionCase = function (icuCase, context) {
throw new Error('Should not be reached');
};
return _Expander;
}());
/**
* @param {?} ast
* @param {?} errors
* @return {?}
*/
function _expandPluralForm(ast, errors) {
var /** @type {?} */ children = ast.cases.map(function (c) {
if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) {
errors.push(new ExpansionError(c.valueSourceSpan, "Plural cases should be \"=<number>\" or one of " + PLURAL_CASES.join(", ")));
}
var /** @type {?} */ expansionResult = expandNodes(c.expression);
errors.push.apply(errors, expansionResult.errors);
return new Element("ng-template", [new Attribute$1('ngPluralCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
});
var /** @type {?} */ switchAttr = new Attribute$1('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan);
return new Element('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
}
/**
* @param {?} ast
* @param {?} errors
* @return {?}
*/
function _expandDefaultForm(ast, errors) {
var /** @type {?} */ children = ast.cases.map(function (c) {
var /** @type {?} */ expansionResult = expandNodes(c.expression);
errors.push.apply(errors, expansionResult.errors);
if (c.value === 'other') {
// other is the default case when no values match
return new Element("ng-template", [new Attribute$1('ngSwitchDefault', '', c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
}
return new Element("ng-template", [new Attribute$1('ngSwitchCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
});
var /** @type {?} */ switchAttr = new Attribute$1('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan);
return new Element('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
}
/**
* @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
*/
var ProviderError = (function (_super) {
__extends(ProviderError, _super);
/**
* @param {?} message
* @param {?} span
*/
function ProviderError(message, span) {
return _super.call(this, span, message) || this;
}
return ProviderError;
}(ParseError));
var ProviderViewContext = (function () {
/**
* @param {?} component
*/
function ProviderViewContext(component) {
var _this = this;
this.component = component;
this.errors = [];
this.viewQueries = _getViewQueries(component);
this.viewProviders = new Map();
component.viewProviders.forEach(function (provider) {
if (_this.viewProviders.get(tokenReference(provider.token)) == null) {
_this.viewProviders.set(tokenReference(provider.token), true);
}
});
}
return ProviderViewContext;
}());
var ProviderElementContext = (function () {
/**
* @param {?} viewContext
* @param {?} _parent
* @param {?} _isViewRoot
* @param {?} _directiveAsts
* @param {?} attrs
* @param {?} refs
* @param {?} isTemplate
* @param {?} contentQueryStartId
* @param {?} _sourceSpan
*/
function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
var _this = this;
this.viewContext = viewContext;
this._parent = _parent;
this._isViewRoot = _isViewRoot;
this._directiveAsts = _directiveAsts;
this._sourceSpan = _sourceSpan;
this._transformedProviders = new Map();
this._seenProviders = new Map();
this._hasViewContainer = false;
this._queriedTokens = new Map();
this._attrs = {};
attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; });
var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; });
this._allProviders =
_resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
Array.from(this._allProviders.values()).forEach(function (provider) {
_this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens);
});
if (isTemplate) {
var templateRefId = createIdentifierToken(Identifiers.TemplateRef);
this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
}
refs.forEach(function (refAst) {
var defaultQueryValue = refAst.value || createIdentifierToken(Identifiers.ElementRef);
_this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens);
});
if (this._queriedTokens.get(resolveIdentifier(Identifiers.ViewContainerRef))) {
this._hasViewContainer = true;
}
// create the providers that we know are eager first
Array.from(this._allProviders.values()).forEach(function (provider) {
var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token));
if (eager) {
_this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
}
});
}
/**
* @return {?}
*/
ProviderElementContext.prototype.afterElement = function () {
var _this = this;
// collect lazy providers
Array.from(this._allProviders.values()).forEach(function (provider) {
_this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
});
};
Object.defineProperty(ProviderElementContext.prototype, "transformProviders", {
/**
* @return {?}
*/
get: function () {
return Array.from(this._transformedProviders.values());
},
enumerable: true,
configurable: true
});
Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; });
var /** @type {?} */ sortedDirectives = this._directiveAsts.slice();
sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) -
sortedProviderTypes.indexOf(dir2.directive.type); });
return sortedDirectives;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ProviderElementContext.prototype, "transformedHasViewContainer", {
/**
* @return {?}
*/
get: function () { return this._hasViewContainer; },
enumerable: true,
configurable: true
});
Object.defineProperty(ProviderElementContext.prototype, "queryMatches", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ allMatches = [];
this._queriedTokens.forEach(function (matches) { allMatches.push.apply(allMatches, matches); });
return allMatches;
},
enumerable: true,
configurable: true
});
/**
* @param {?} token
* @param {?} defaultValue
* @param {?} queryReadTokens
* @return {?}
*/
ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) {
this._getQueriesFor(token).forEach(function (query) {
var /** @type {?} */ queryValue = query.meta.read || defaultValue;
var /** @type {?} */ tokenRef = tokenReference(queryValue);
var /** @type {?} */ queryMatches = queryReadTokens.get(tokenRef);
if (!queryMatches) {
queryMatches = [];
queryReadTokens.set(tokenRef, queryMatches);
}
queryMatches.push({ queryId: query.queryId, value: queryValue });
});
};
/**
* @param {?} token
* @return {?}
*/
ProviderElementContext.prototype._getQueriesFor = function (token) {
var /** @type {?} */ result = [];
var /** @type {?} */ currentEl = this;
var /** @type {?} */ distance = 0;
var /** @type {?} */ queries;
while (currentEl !== null) {
queries = currentEl._contentQueries.get(tokenReference(token));
if (queries) {
result.push.apply(result, queries.filter(function (query) { return query.meta.descendants || distance <= 1; }));
}
if (currentEl._directiveAsts.length > 0) {
distance++;
}
currentEl = currentEl._parent;
}
queries = this.viewContext.viewQueries.get(tokenReference(token));
if (queries) {
result.push.apply(result, queries);
}
return result;
};
/**
* @param {?} requestingProviderType
* @param {?} token
* @param {?} eager
* @return {?}
*/
ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) {
var _this = this;
var /** @type {?} */ resolvedProvider = this._allProviders.get(tokenReference(token));
if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive ||
requestingProviderType === ProviderAstType.PublicService) &&
resolvedProvider.providerType === ProviderAstType.PrivateService) ||
((requestingProviderType === ProviderAstType.PrivateService ||
requestingProviderType === ProviderAstType.PublicService) &&
resolvedProvider.providerType === ProviderAstType.Builtin)) {
return null;
}
var /** @type {?} */ transformedProviderAst = this._transformedProviders.get(tokenReference(token));
if (transformedProviderAst) {
return transformedProviderAst;
}
if (this._seenProviders.get(tokenReference(token)) != null) {
this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan));
return null;
}
this._seenProviders.set(tokenReference(token), true);
var /** @type {?} */ transformedProviders = resolvedProvider.providers.map(function (provider) {
var /** @type {?} */ transformedUseValue = provider.useValue;
var /** @type {?} */ transformedUseExisting = ((provider.useExisting));
var /** @type {?} */ transformedDeps = ((undefined));
if (provider.useExisting != null) {
var /** @type {?} */ existingDiDep = ((_this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager)));
if (existingDiDep.token != null) {
transformedUseExisting = existingDiDep.token;
}
else {
transformedUseExisting = ((null));
transformedUseValue = existingDiDep.value;
}
}
else if (provider.useFactory) {
var /** @type {?} */ deps = provider.deps || provider.useFactory.diDeps;
transformedDeps =
deps.map(function (dep) { return ((_this._getDependency(resolvedProvider.providerType, dep, eager))); });
}
else if (provider.useClass) {
var /** @type {?} */ deps = provider.deps || provider.useClass.diDeps;
transformedDeps =
deps.map(function (dep) { return ((_this._getDependency(resolvedProvider.providerType, dep, eager))); });
}
return _transformProvider(provider, {
useExisting: transformedUseExisting,
useValue: transformedUseValue,
deps: transformedDeps
});
});
transformedProviderAst =
_transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
this._transformedProviders.set(tokenReference(token), transformedProviderAst);
return transformedProviderAst;
};
/**
* @param {?} requestingProviderType
* @param {?} dep
* @param {?=} eager
* @return {?}
*/
ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) {
if (eager === void 0) { eager = false; }
if (dep.isAttribute) {
var /** @type {?} */ attrValue = this._attrs[((dep.token)).value];
return { isValue: true, value: attrValue == null ? null : attrValue };
}
if (dep.token != null) {
// access builtints
if ((requestingProviderType === ProviderAstType.Directive ||
requestingProviderType === ProviderAstType.Component)) {
if (tokenReference(dep.token) === resolveIdentifier(Identifiers.Renderer) ||
tokenReference(dep.token) === resolveIdentifier(Identifiers.ElementRef) ||
tokenReference(dep.token) === resolveIdentifier(Identifiers.ChangeDetectorRef) ||
tokenReference(dep.token) === resolveIdentifier(Identifiers.TemplateRef)) {
return dep;
}
if (tokenReference(dep.token) === resolveIdentifier(Identifiers.ViewContainerRef)) {
this._hasViewContainer = true;
}
}
// access the injector
if (tokenReference(dep.token) === resolveIdentifier(Identifiers.Injector)) {
return dep;
}
// access providers
if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
return dep;
}
}
return null;
};
/**
* @param {?} requestingProviderType
* @param {?} dep
* @param {?=} eager
* @return {?}
*/
ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) {
if (eager === void 0) { eager = false; }
var /** @type {?} */ currElement = this;
var /** @type {?} */ currEager = eager;
var /** @type {?} */ result = null;
if (!dep.isSkipSelf) {
result = this._getLocalDependency(requestingProviderType, dep, eager);
}
if (dep.isSelf) {
if (!result && dep.isOptional) {
result = { isValue: true, value: null };
}
}
else {
// check parent elements
while (!result && currElement._parent) {
var /** @type {?} */ prevElement = currElement;
currElement = currElement._parent;
if (prevElement._isViewRoot) {
currEager = false;
}
result = currElement._getLocalDependency(ProviderAstType.PublicService, dep, currEager);
}
// check @Host restriction
if (!result) {
if (!dep.isHost || this.viewContext.component.isHost ||
this.viewContext.component.type.reference === tokenReference(/** @type {?} */ ((dep.token))) ||
this.viewContext.viewProviders.get(tokenReference(/** @type {?} */ ((dep.token)))) != null) {
result = dep;
}
else {
result = dep.isOptional ? result = { isValue: true, value: null } : null;
}
}
}
if (!result) {
this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(/** @type {?} */ ((dep.token))), this._sourceSpan));
}
return result;
};
return ProviderElementContext;
}());
var NgModuleProviderAnalyzer = (function () {
/**
* @param {?} ngModule
* @param {?} extraProviders
* @param {?} sourceSpan
*/
function NgModuleProviderAnalyzer(ngModule, extraProviders, sourceSpan) {
var _this = this;
this._transformedProviders = new Map();
this._seenProviders = new Map();
this._errors = [];
this._allProviders = new Map();
ngModule.transitiveModule.modules.forEach(function (ngModuleType) {
var ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType };
_resolveProviders([ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, _this._errors, _this._allProviders);
});
_resolveProviders(ngModule.transitiveModule.providers.map(function (entry) { return entry.provider; }).concat(extraProviders), ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders);
}
/**
* @return {?}
*/
NgModuleProviderAnalyzer.prototype.parse = function () {
var _this = this;
Array.from(this._allProviders.values()).forEach(function (provider) {
_this._getOrCreateLocalProvider(provider.token, provider.eager);
});
if (this._errors.length > 0) {
var /** @type {?} */ errorString = this._errors.join('\n');
throw new Error("Provider parse errors:\n" + errorString);
}
return Array.from(this._transformedProviders.values());
};
/**
* @param {?} token
* @param {?} eager
* @return {?}
*/
NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) {
var _this = this;
var /** @type {?} */ resolvedProvider = this._allProviders.get(tokenReference(token));
if (!resolvedProvider) {
return null;
}
var /** @type {?} */ transformedProviderAst = this._transformedProviders.get(tokenReference(token));
if (transformedProviderAst) {
return transformedProviderAst;
}
if (this._seenProviders.get(tokenReference(token)) != null) {
this._errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), resolvedProvider.sourceSpan));
return null;
}
this._seenProviders.set(tokenReference(token), true);
var /** @type {?} */ transformedProviders = resolvedProvider.providers.map(function (provider) {
var /** @type {?} */ transformedUseValue = provider.useValue;
var /** @type {?} */ transformedUseExisting = ((provider.useExisting));
var /** @type {?} */ transformedDeps = ((undefined));
if (provider.useExisting != null) {
var /** @type {?} */ existingDiDep = _this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan);
if (existingDiDep.token != null) {
transformedUseExisting = existingDiDep.token;
}
else {
transformedUseExisting = ((null));
transformedUseValue = existingDiDep.value;
}
}
else if (provider.useFactory) {
var /** @type {?} */ deps = provider.deps || provider.useFactory.diDeps;
transformedDeps =
deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
}
else if (provider.useClass) {
var /** @type {?} */ deps = provider.deps || provider.useClass.diDeps;
transformedDeps =
deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
}
return _transformProvider(provider, {
useExisting: transformedUseExisting,
useValue: transformedUseValue,
deps: transformedDeps
});
});
transformedProviderAst =
_transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
this._transformedProviders.set(tokenReference(token), transformedProviderAst);
return transformedProviderAst;
};
/**
* @param {?} dep
* @param {?=} eager
* @param {?=} requestorSourceSpan
* @return {?}
*/
NgModuleProviderAnalyzer.prototype._getDependency = function (dep, eager, requestorSourceSpan) {
if (eager === void 0) { eager = false; }
var /** @type {?} */ foundLocal = false;
if (!dep.isSkipSelf && dep.token != null) {
// access the injector
if (tokenReference(dep.token) === resolveIdentifier(Identifiers.Injector) ||
tokenReference(dep.token) === resolveIdentifier(Identifiers.ComponentFactoryResolver)) {
foundLocal = true;
}
else if (this._getOrCreateLocalProvider(dep.token, eager) != null) {
foundLocal = true;
}
}
var /** @type {?} */ result = dep;
if (dep.isSelf && !foundLocal) {
if (dep.isOptional) {
result = { isValue: true, value: null };
}
else {
this._errors.push(new ProviderError("No provider for " + tokenName(/** @type {?} */ ((dep.token))), requestorSourceSpan));
}
}
return result;
};
return NgModuleProviderAnalyzer;
}());
/**
* @param {?} provider
* @param {?} __1
* @return {?}
*/
function _transformProvider(provider, _a) {
var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps;
return {
token: provider.token,
useClass: provider.useClass,
useExisting: useExisting,
useFactory: provider.useFactory,
useValue: useValue,
deps: deps,
multi: provider.multi
};
}
/**
* @param {?} provider
* @param {?} __1
* @return {?}
*/
function _transformProviderAst(provider, _a) {
var eager = _a.eager, providers = _a.providers;
return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan);
}
/**
* @param {?} directives
* @param {?} sourceSpan
* @param {?} targetErrors
* @return {?}
*/
function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) {
var /** @type {?} */ providersByToken = new Map();
directives.forEach(function (directive) {
var /** @type {?} */ dirProvider = { token: { identifier: directive.type }, useClass: directive.type };
_resolveProviders([dirProvider], directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken);
});
// Note: directives need to be able to overwrite providers of a component!
var /** @type {?} */ directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; }));
directivesWithComponentFirst.forEach(function (directive) {
_resolveProviders(directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken);
_resolveProviders(directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken);
});
return providersByToken;
}
/**
* @param {?} providers
* @param {?} providerType
* @param {?} eager
* @param {?} sourceSpan
* @param {?} targetErrors
* @param {?} targetProvidersByToken
* @return {?}
*/
function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken) {
providers.forEach(function (provider) {
var /** @type {?} */ resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan));
}
if (!resolvedProvider) {
var /** @type {?} */ lifecycleHooks = provider.token.identifier &&
((provider.token.identifier)).lifecycleHooks ?
((provider.token.identifier)).lifecycleHooks :
[];
var /** @type {?} */ isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);
resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan);
targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);
}
else {
if (!provider.multi) {
resolvedProvider.providers.length = 0;
}
resolvedProvider.providers.push(provider);
}
});
}
/**
* @param {?} component
* @return {?}
*/
function _getViewQueries(component) {
// Note: queries start with id 1 so we can use the number in a Bloom filter!
var /** @type {?} */ viewQueryId = 1;
var /** @type {?} */ viewQueries = new Map();
if (component.viewQueries) {
component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); });
}
return viewQueries;
}
/**
* @param {?} contentQueryStartId
* @param {?} directives
* @return {?}
*/
function _getContentQueries(contentQueryStartId, directives) {
var /** @type {?} */ contentQueryId = contentQueryStartId;
var /** @type {?} */ contentQueries = new Map();
directives.forEach(function (directive, directiveIndex) {
if (directive.queries) {
directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); });
}
});
return contentQueries;
}
/**
* @param {?} map
* @param {?} query
* @return {?}
*/
function _addQueryToTokenMap(map, query) {
query.meta.selectors.forEach(function (token) {
var /** @type {?} */ entry = map.get(tokenReference(token));
if (!entry) {
entry = [];
map.set(tokenReference(token), entry);
}
entry.push(query);
});
}
/**
* @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
*/
/**
* @abstract
*/
var ElementSchemaRegistry = (function () {
function ElementSchemaRegistry() {
}
/**
* @abstract
* @param {?} tagName
* @param {?} propName
* @param {?} schemaMetas
* @return {?}
*/
ElementSchemaRegistry.prototype.hasProperty = function (tagName, propName, schemaMetas) { };
/**
* @abstract
* @param {?} tagName
* @param {?} schemaMetas
* @return {?}
*/
ElementSchemaRegistry.prototype.hasElement = function (tagName, schemaMetas) { };
/**
* @abstract
* @param {?} elementName
* @param {?} propName
* @param {?} isAttribute
* @return {?}
*/
ElementSchemaRegistry.prototype.securityContext = function (elementName, propName, isAttribute) { };
/**
* @abstract
* @return {?}
*/
ElementSchemaRegistry.prototype.allKnownElementNames = function () { };
/**
* @abstract
* @param {?} propName
* @return {?}
*/
ElementSchemaRegistry.prototype.getMappedPropName = function (propName) { };
/**
* @abstract
* @return {?}
*/
ElementSchemaRegistry.prototype.getDefaultComponentElementName = function () { };
/**
* @abstract
* @param {?} name
* @return {?}
*/
ElementSchemaRegistry.prototype.validateProperty = function (name) { };
/**
* @abstract
* @param {?} name
* @return {?}
*/
ElementSchemaRegistry.prototype.validateAttribute = function (name) { };
/**
* @abstract
* @param {?} propName
* @return {?}
*/
ElementSchemaRegistry.prototype.normalizeAnimationStyleProperty = function (propName) { };
/**
* @abstract
* @param {?} camelCaseProp
* @param {?} userProvidedProp
* @param {?} val
* @return {?}
*/
ElementSchemaRegistry.prototype.normalizeAnimationStyleValue = function (camelCaseProp, userProvidedProp, val) { };
return ElementSchemaRegistry;
}());
/**
* @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
*/
var StyleWithImports = (function () {
/**
* @param {?} style
* @param {?} styleUrls
*/
function StyleWithImports(style$$1, styleUrls) {
this.style = style$$1;
this.styleUrls = styleUrls;
}
return StyleWithImports;
}());
/**
* @param {?} url
* @return {?}
*/
function isStyleUrlResolvable(url) {
if (url == null || url.length === 0 || url[0] == '/')
return false;
var /** @type {?} */ schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
}
/**
* Rewrites stylesheets by resolving and removing the \@import urls that
* are either relative or don't have a `package:` scheme
* @param {?} resolver
* @param {?} baseUrl
* @param {?} cssText
* @return {?}
*/
function extractStyleUrls(resolver, baseUrl, cssText) {
var /** @type {?} */ foundUrls = [];
var /** @type {?} */ modifiedCssText = cssText.replace(CSS_COMMENT_REGEXP, '').replace(CSS_IMPORT_REGEXP, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
var /** @type {?} */ url = m[1] || m[2];
if (!isStyleUrlResolvable(url)) {
// Do not attempt to resolve non-package absolute URLs with URI scheme
return m[0];
}
foundUrls.push(resolver.resolve(baseUrl, url));
return '';
});
return new StyleWithImports(modifiedCssText, foundUrls);
}
var CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
var CSS_COMMENT_REGEXP = /\/\*.+?\*\//g;
var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
/**
* @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
*/
var PROPERTY_PARTS_SEPARATOR = '.';
var ATTRIBUTE_PREFIX = 'attr';
var CLASS_PREFIX = 'class';
var STYLE_PREFIX = 'style';
var ANIMATE_PROP_PREFIX = 'animate-';
var BoundPropertyType = {};
BoundPropertyType.DEFAULT = 0;
BoundPropertyType.LITERAL_ATTR = 1;
BoundPropertyType.ANIMATION = 2;
BoundPropertyType[BoundPropertyType.DEFAULT] = "DEFAULT";
BoundPropertyType[BoundPropertyType.LITERAL_ATTR] = "LITERAL_ATTR";
BoundPropertyType[BoundPropertyType.ANIMATION] = "ANIMATION";
/**
* Represents a parsed property.
*/
var BoundProperty = (function () {
/**
* @param {?} name
* @param {?} expression
* @param {?} type
* @param {?} sourceSpan
*/
function BoundProperty(name, expression, type, sourceSpan) {
this.name = name;
this.expression = expression;
this.type = type;
this.sourceSpan = sourceSpan;
}
Object.defineProperty(BoundProperty.prototype, "isLiteral", {
/**
* @return {?}
*/
get: function () { return this.type === BoundPropertyType.LITERAL_ATTR; },
enumerable: true,
configurable: true
});
Object.defineProperty(BoundProperty.prototype, "isAnimation", {
/**
* @return {?}
*/
get: function () { return this.type === BoundPropertyType.ANIMATION; },
enumerable: true,
configurable: true
});
return BoundProperty;
}());
/**
* Parses bindings in templates and in the directive host area.
*/
var BindingParser = (function () {
/**
* @param {?} _exprParser
* @param {?} _interpolationConfig
* @param {?} _schemaRegistry
* @param {?} pipes
* @param {?} _targetErrors
*/
function BindingParser(_exprParser, _interpolationConfig, _schemaRegistry, pipes, _targetErrors) {
var _this = this;
this._exprParser = _exprParser;
this._interpolationConfig = _interpolationConfig;
this._schemaRegistry = _schemaRegistry;
this._targetErrors = _targetErrors;
this.pipesByName = new Map();
this._usedPipes = new Map();
pipes.forEach(function (pipe) { return _this.pipesByName.set(pipe.name, pipe); });
}
/**
* @return {?}
*/
BindingParser.prototype.getUsedPipes = function () { return Array.from(this._usedPipes.values()); };
/**
* @param {?} dirMeta
* @param {?} elementSelector
* @param {?} sourceSpan
* @return {?}
*/
BindingParser.prototype.createDirectiveHostPropertyAsts = function (dirMeta, elementSelector, sourceSpan) {
var _this = this;
if (dirMeta.hostProperties) {
var /** @type {?} */ boundProps_1 = [];
Object.keys(dirMeta.hostProperties).forEach(function (propName) {
var /** @type {?} */ expression = dirMeta.hostProperties[propName];
if (typeof expression === 'string') {
_this.parsePropertyBinding(propName, expression, true, sourceSpan, [], boundProps_1);
}
else {
_this._reportError("Value of the host property binding \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
}
});
return boundProps_1.map(function (prop) { return _this.createElementPropertyAst(elementSelector, prop); });
}
return null;
};
/**
* @param {?} dirMeta
* @param {?} sourceSpan
* @return {?}
*/
BindingParser.prototype.createDirectiveHostEventAsts = function (dirMeta, sourceSpan) {
var _this = this;
if (dirMeta.hostListeners) {
var /** @type {?} */ targetEventAsts_1 = [];
Object.keys(dirMeta.hostListeners).forEach(function (propName) {
var /** @type {?} */ expression = dirMeta.hostListeners[propName];
if (typeof expression === 'string') {
_this.parseEvent(propName, expression, sourceSpan, [], targetEventAsts_1);
}
else {
_this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
}
});
return targetEventAsts_1;
}
return null;
};
/**
* @param {?} value
* @param {?} sourceSpan
* @return {?}
*/
BindingParser.prototype.parseInterpolation = function (value, sourceSpan) {
var /** @type {?} */ sourceInfo = sourceSpan.start.toString();
try {
var /** @type {?} */ ast = ((this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig)));
if (ast)
this._reportExpressionParserErrors(ast.errors, sourceSpan);
this._checkPipes(ast, sourceSpan);
return ast;
}
catch (e) {
this._reportError("" + e, sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
}
};
/**
* @param {?} prefixToken
* @param {?} value
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetProps
* @param {?} targetVars
* @return {?}
*/
BindingParser.prototype.parseInlineTemplateBinding = function (prefixToken, value, sourceSpan, targetMatchableAttrs, targetProps, targetVars) {
var /** @type {?} */ bindings = this._parseTemplateBindings(prefixToken, value, sourceSpan);
for (var /** @type {?} */ i = 0; i < bindings.length; i++) {
var /** @type {?} */ binding = bindings[i];
if (binding.keyIsVar) {
targetVars.push(new VariableAst(binding.key, binding.name, sourceSpan));
}
else if (binding.expression) {
this._parsePropertyAst(binding.key, binding.expression, sourceSpan, targetMatchableAttrs, targetProps);
}
else {
targetMatchableAttrs.push([binding.key, '']);
this.parseLiteralAttr(binding.key, null, sourceSpan, targetMatchableAttrs, targetProps);
}
}
};
/**
* @param {?} prefixToken
* @param {?} value
* @param {?} sourceSpan
* @return {?}
*/
BindingParser.prototype._parseTemplateBindings = function (prefixToken, value, sourceSpan) {
var _this = this;
var /** @type {?} */ sourceInfo = sourceSpan.start.toString();
try {
var /** @type {?} */ bindingsResult = this._exprParser.parseTemplateBindings(prefixToken, value, sourceInfo);
this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
bindingsResult.templateBindings.forEach(function (binding) {
if (binding.expression) {
_this._checkPipes(binding.expression, sourceSpan);
}
});
bindingsResult.warnings.forEach(function (warning) { _this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); });
return bindingsResult.templateBindings;
}
catch (e) {
this._reportError("" + e, sourceSpan);
return [];
}
};
/**
* @param {?} name
* @param {?} value
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetProps
* @return {?}
*/
BindingParser.prototype.parseLiteralAttr = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
if (_isAnimationLabel(name)) {
name = name.substring(1);
if (value) {
this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." +
" Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", sourceSpan, ParseErrorLevel.ERROR);
}
this._parseAnimation(name, value, sourceSpan, targetMatchableAttrs, targetProps);
}
else {
targetProps.push(new BoundProperty(name, this._exprParser.wrapLiteralPrimitive(value, ''), BoundPropertyType.LITERAL_ATTR, sourceSpan));
}
};
/**
* @param {?} name
* @param {?} expression
* @param {?} isHost
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetProps
* @return {?}
*/
BindingParser.prototype.parsePropertyBinding = function (name, expression, isHost, sourceSpan, targetMatchableAttrs, targetProps) {
var /** @type {?} */ isAnimationProp = false;
if (name.startsWith(ANIMATE_PROP_PREFIX)) {
isAnimationProp = true;
name = name.substring(ANIMATE_PROP_PREFIX.length);
}
else if (_isAnimationLabel(name)) {
isAnimationProp = true;
name = name.substring(1);
}
if (isAnimationProp) {
this._parseAnimation(name, expression, sourceSpan, targetMatchableAttrs, targetProps);
}
else {
this._parsePropertyAst(name, this._parseBinding(expression, isHost, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps);
}
};
/**
* @param {?} name
* @param {?} value
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetProps
* @return {?}
*/
BindingParser.prototype.parsePropertyInterpolation = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
var /** @type {?} */ expr = this.parseInterpolation(value, sourceSpan);
if (expr) {
this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps);
return true;
}
return false;
};
/**
* @param {?} name
* @param {?} ast
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetProps
* @return {?}
*/
BindingParser.prototype._parsePropertyAst = function (name, ast, sourceSpan, targetMatchableAttrs, targetProps) {
targetMatchableAttrs.push([name, /** @type {?} */ ((ast.source))]);
targetProps.push(new BoundProperty(name, ast, BoundPropertyType.DEFAULT, sourceSpan));
};
/**
* @param {?} name
* @param {?} expression
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetProps
* @return {?}
*/
BindingParser.prototype._parseAnimation = function (name, expression, sourceSpan, targetMatchableAttrs, targetProps) {
// This will occur when a @trigger is not paired with an expression.
// For animations it is valid to not have an expression since */void
// states will be applied by angular when the element is attached/detached
var /** @type {?} */ ast = this._parseBinding(expression || 'null', false, sourceSpan);
targetMatchableAttrs.push([name, /** @type {?} */ ((ast.source))]);
targetProps.push(new BoundProperty(name, ast, BoundPropertyType.ANIMATION, sourceSpan));
};
/**
* @param {?} value
* @param {?} isHostBinding
* @param {?} sourceSpan
* @return {?}
*/
BindingParser.prototype._parseBinding = function (value, isHostBinding, sourceSpan) {
var /** @type {?} */ sourceInfo = sourceSpan.start.toString();
try {
var /** @type {?} */ ast = isHostBinding ?
this._exprParser.parseSimpleBinding(value, sourceInfo, this._interpolationConfig) :
this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig);
if (ast)
this._reportExpressionParserErrors(ast.errors, sourceSpan);
this._checkPipes(ast, sourceSpan);
return ast;
}
catch (e) {
this._reportError("" + e, sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
}
};
/**
* @param {?} elementSelector
* @param {?} boundProp
* @return {?}
*/
BindingParser.prototype.createElementPropertyAst = function (elementSelector, boundProp) {
if (boundProp.isAnimation) {
return new BoundElementPropertyAst(boundProp.name, PropertyBindingType.Animation, __WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].NONE, boundProp.expression, null, boundProp.sourceSpan);
}
var /** @type {?} */ unit = null;
var /** @type {?} */ bindingType = ((undefined));
var /** @type {?} */ boundPropertyName = null;
var /** @type {?} */ parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
var /** @type {?} */ securityContexts = ((undefined));
// Check check for special cases (prefix style, attr, class)
if (parts.length > 1) {
if (parts[0] == ATTRIBUTE_PREFIX) {
boundPropertyName = parts[1];
this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true);
var /** @type {?} */ nsSeparatorIdx = boundPropertyName.indexOf(':');
if (nsSeparatorIdx > -1) {
var /** @type {?} */ ns = boundPropertyName.substring(0, nsSeparatorIdx);
var /** @type {?} */ name = boundPropertyName.substring(nsSeparatorIdx + 1);
boundPropertyName = mergeNsAndName(ns, name);
}
bindingType = PropertyBindingType.Attribute;
}
else if (parts[0] == CLASS_PREFIX) {
boundPropertyName = parts[1];
bindingType = PropertyBindingType.Class;
securityContexts = [__WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].NONE];
}
else if (parts[0] == STYLE_PREFIX) {
unit = parts.length > 2 ? parts[2] : null;
boundPropertyName = parts[1];
bindingType = PropertyBindingType.Style;
securityContexts = [__WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].STYLE];
}
}
// If not a special case, use the full property name
if (boundPropertyName === null) {
boundPropertyName = this._schemaRegistry.getMappedPropName(boundProp.name);
securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, false);
bindingType = PropertyBindingType.Property;
this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, false);
}
return new BoundElementPropertyAst(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan);
};
/**
* @param {?} name
* @param {?} expression
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetEvents
* @return {?}
*/
BindingParser.prototype.parseEvent = function (name, expression, sourceSpan, targetMatchableAttrs, targetEvents) {
if (_isAnimationLabel(name)) {
name = name.substr(1);
this._parseAnimationEvent(name, expression, sourceSpan, targetEvents);
}
else {
this._parseEvent(name, expression, sourceSpan, targetMatchableAttrs, targetEvents);
}
};
/**
* @param {?} name
* @param {?} expression
* @param {?} sourceSpan
* @param {?} targetEvents
* @return {?}
*/
BindingParser.prototype._parseAnimationEvent = function (name, expression, sourceSpan, targetEvents) {
var /** @type {?} */ matches = splitAtPeriod(name, [name, '']);
var /** @type {?} */ eventName = matches[0];
var /** @type {?} */ phase = matches[1].toLowerCase();
if (phase) {
switch (phase) {
case 'start':
case 'done':
var /** @type {?} */ ast = this._parseAction(expression, sourceSpan);
targetEvents.push(new BoundEventAst(eventName, null, phase, ast, sourceSpan));
break;
default:
this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan);
break;
}
}
else {
this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan);
}
};
/**
* @param {?} name
* @param {?} expression
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetEvents
* @return {?}
*/
BindingParser.prototype._parseEvent = function (name, expression, sourceSpan, targetMatchableAttrs, targetEvents) {
// long format: 'target: eventName'
var _a = splitAtColon(name, [/** @type {?} */ ((null)), name]), target = _a[0], eventName = _a[1];
var /** @type {?} */ ast = this._parseAction(expression, sourceSpan);
targetMatchableAttrs.push([/** @type {?} */ ((name)), /** @type {?} */ ((ast.source))]);
targetEvents.push(new BoundEventAst(eventName, target, null, ast, sourceSpan));
// Don't detect directives for event names for now,
// so don't add the event name to the matchableAttrs
};
/**
* @param {?} value
* @param {?} sourceSpan
* @return {?}
*/
BindingParser.prototype._parseAction = function (value, sourceSpan) {
var /** @type {?} */ sourceInfo = sourceSpan.start.toString();
try {
var /** @type {?} */ ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig);
if (ast) {
this._reportExpressionParserErrors(ast.errors, sourceSpan);
}
if (!ast || ast.ast instanceof EmptyExpr) {
this._reportError("Empty expressions are not allowed", sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
}
this._checkPipes(ast, sourceSpan);
return ast;
}
catch (e) {
this._reportError("" + e, sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
}
};
/**
* @param {?} message
* @param {?} sourceSpan
* @param {?=} level
* @return {?}
*/
BindingParser.prototype._reportError = function (message, sourceSpan, level) {
if (level === void 0) { level = ParseErrorLevel.ERROR; }
this._targetErrors.push(new ParseError(sourceSpan, message, level));
};
/**
* @param {?} errors
* @param {?} sourceSpan
* @return {?}
*/
BindingParser.prototype._reportExpressionParserErrors = function (errors, sourceSpan) {
for (var _i = 0, errors_1 = errors; _i < errors_1.length; _i++) {
var error = errors_1[_i];
this._reportError(error.message, sourceSpan);
}
};
/**
* @param {?} ast
* @param {?} sourceSpan
* @return {?}
*/
BindingParser.prototype._checkPipes = function (ast, sourceSpan) {
var _this = this;
if (ast) {
var /** @type {?} */ collector = new PipeCollector();
ast.visit(collector);
collector.pipes.forEach(function (ast, pipeName) {
var /** @type {?} */ pipeMeta = _this.pipesByName.get(pipeName);
if (!pipeMeta) {
_this._reportError("The pipe '" + pipeName + "' could not be found", new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end)));
}
else {
_this._usedPipes.set(pipeName, pipeMeta);
}
});
}
};
/**
* @param {?} propName the name of the property / attribute
* @param {?} sourceSpan
* @param {?} isAttr true when binding to an attribute
* @return {?}
*/
BindingParser.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) {
var /** @type {?} */ report = isAttr ? this._schemaRegistry.validateAttribute(propName) :
this._schemaRegistry.validateProperty(propName);
if (report.error) {
this._reportError(/** @type {?} */ ((report.msg)), sourceSpan, ParseErrorLevel.ERROR);
}
};
return BindingParser;
}());
var PipeCollector = (function (_super) {
__extends(PipeCollector, _super);
function PipeCollector() {
var _this = _super.apply(this, arguments) || this;
_this.pipes = new Map();
return _this;
}
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
PipeCollector.prototype.visitPipe = function (ast, context) {
this.pipes.set(ast.name, ast);
ast.exp.visit(this);
this.visitAll(ast.args, context);
return null;
};
return PipeCollector;
}(RecursiveAstVisitor));
/**
* @param {?} name
* @return {?}
*/
function _isAnimationLabel(name) {
return name[0] == '@';
}
/**
* @param {?} registry
* @param {?} selector
* @param {?} propName
* @param {?} isAttribute
* @return {?}
*/
function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
var /** @type {?} */ ctxs = [];
CssSelector.parse(selector).forEach(function (selector) {
var /** @type {?} */ elementNames = selector.element ? [selector.element] : registry.allKnownElementNames();
var /** @type {?} */ notElementNames = new Set(selector.notSelectors.filter(function (selector) { return selector.isElementSelector(); })
.map(function (selector) { return selector.element; }));
var /** @type {?} */ possibleElementNames = elementNames.filter(function (elementName) { return !notElementNames.has(elementName); });
ctxs.push.apply(ctxs, possibleElementNames.map(function (elementName) { return registry.securityContext(elementName, propName, isAttribute); }));
});
return ctxs.length === 0 ? [__WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].NONE] : Array.from(new Set(ctxs)).sort();
}
/**
* @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
*/
var NG_CONTENT_SELECT_ATTR = 'select';
var LINK_ELEMENT = 'link';
var LINK_STYLE_REL_ATTR = 'rel';
var LINK_STYLE_HREF_ATTR = 'href';
var LINK_STYLE_REL_VALUE = 'stylesheet';
var STYLE_ELEMENT = 'style';
var SCRIPT_ELEMENT = 'script';
var NG_NON_BINDABLE_ATTR = 'ngNonBindable';
var NG_PROJECT_AS = 'ngProjectAs';
/**
* @param {?} ast
* @return {?}
*/
function preparseElement(ast) {
var /** @type {?} */ selectAttr = ((null));
var /** @type {?} */ hrefAttr = ((null));
var /** @type {?} */ relAttr = ((null));
var /** @type {?} */ nonBindable = false;
var /** @type {?} */ projectAs = ((null));
ast.attrs.forEach(function (attr) {
var /** @type {?} */ lcAttrName = attr.name.toLowerCase();
if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
selectAttr = attr.value;
}
else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
hrefAttr = attr.value;
}
else if (lcAttrName == LINK_STYLE_REL_ATTR) {
relAttr = attr.value;
}
else if (attr.name == NG_NON_BINDABLE_ATTR) {
nonBindable = true;
}
else if (attr.name == NG_PROJECT_AS) {
if (attr.value.length > 0) {
projectAs = attr.value;
}
}
});
selectAttr = normalizeNgContentSelect(selectAttr);
var /** @type {?} */ nodeName = ast.name.toLowerCase();
var /** @type {?} */ type = PreparsedElementType.OTHER;
if (isNgContent(nodeName)) {
type = PreparsedElementType.NG_CONTENT;
}
else if (nodeName == STYLE_ELEMENT) {
type = PreparsedElementType.STYLE;
}
else if (nodeName == SCRIPT_ELEMENT) {
type = PreparsedElementType.SCRIPT;
}
else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
type = PreparsedElementType.STYLESHEET;
}
return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs);
}
var PreparsedElementType = {};
PreparsedElementType.NG_CONTENT = 0;
PreparsedElementType.STYLE = 1;
PreparsedElementType.STYLESHEET = 2;
PreparsedElementType.SCRIPT = 3;
PreparsedElementType.OTHER = 4;
PreparsedElementType[PreparsedElementType.NG_CONTENT] = "NG_CONTENT";
PreparsedElementType[PreparsedElementType.STYLE] = "STYLE";
PreparsedElementType[PreparsedElementType.STYLESHEET] = "STYLESHEET";
PreparsedElementType[PreparsedElementType.SCRIPT] = "SCRIPT";
PreparsedElementType[PreparsedElementType.OTHER] = "OTHER";
var PreparsedElement = (function () {
/**
* @param {?} type
* @param {?} selectAttr
* @param {?} hrefAttr
* @param {?} nonBindable
* @param {?} projectAs
*/
function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) {
this.type = type;
this.selectAttr = selectAttr;
this.hrefAttr = hrefAttr;
this.nonBindable = nonBindable;
this.projectAs = projectAs;
}
return PreparsedElement;
}());
/**
* @param {?} selectAttr
* @return {?}
*/
function normalizeNgContentSelect(selectAttr) {
if (selectAttr === null || selectAttr.length === 0) {
return '*';
}
return selectAttr;
}
/**
* @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
*/
var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
// Group 1 = "bind-"
var KW_BIND_IDX = 1;
// Group 2 = "let-"
var KW_LET_IDX = 2;
// Group 3 = "ref-/#"
var KW_REF_IDX = 3;
// Group 4 = "on-"
var KW_ON_IDX = 4;
// Group 5 = "bindon-"
var KW_BINDON_IDX = 5;
// Group 6 = "@"
var KW_AT_IDX = 6;
// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
var IDENT_KW_IDX = 7;
// Group 8 = identifier inside [()]
var IDENT_BANANA_BOX_IDX = 8;
// Group 9 = identifier inside []
var IDENT_PROPERTY_IDX = 9;
// Group 10 = identifier inside ()
var IDENT_EVENT_IDX = 10;
// deprecated in 4.x
var TEMPLATE_ELEMENT = 'template';
// deprecated in 4.x
var TEMPLATE_ATTR = 'template';
var TEMPLATE_ATTR_PREFIX = '*';
var CLASS_ATTR = 'class';
var TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
var TEMPLATE_ELEMENT_DEPRECATION_WARNING = 'The <template> element is deprecated. Use <ng-template> instead';
var TEMPLATE_ATTR_DEPRECATION_WARNING = 'The template attribute is deprecated. Use an ng-template element instead.';
var warningCounts = {};
/**
* @param {?} warnings
* @return {?}
*/
function warnOnlyOnce(warnings) {
return function (error) {
if (warnings.indexOf(error.msg) !== -1) {
warningCounts[error.msg] = (warningCounts[error.msg] || 0) + 1;
return warningCounts[error.msg] <= 1;
}
return true;
};
}
/**
* Provides an array of {@link TemplateAstVisitor}s which will be used to transform
* parsed templates before compilation is invoked, allowing custom expression syntax
* and other advanced transformations.
*
* This is currently an internal-only feature and not meant for general use.
*/
var TEMPLATE_TRANSFORMS = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('TemplateTransforms');
var TemplateParseError = (function (_super) {
__extends(TemplateParseError, _super);
/**
* @param {?} message
* @param {?} span
* @param {?} level
*/
function TemplateParseError(message, span, level) {
return _super.call(this, span, message, level) || this;
}
return TemplateParseError;
}(ParseError));
var TemplateParseResult = (function () {
/**
* @param {?=} templateAst
* @param {?=} usedPipes
* @param {?=} errors
*/
function TemplateParseResult(templateAst, usedPipes, errors) {
this.templateAst = templateAst;
this.usedPipes = usedPipes;
this.errors = errors;
}
return TemplateParseResult;
}());
var TemplateParser = (function () {
/**
* @param {?} _config
* @param {?} _exprParser
* @param {?} _schemaRegistry
* @param {?} _htmlParser
* @param {?} _console
* @param {?} transforms
*/
function TemplateParser(_config, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) {
this._config = _config;
this._exprParser = _exprParser;
this._schemaRegistry = _schemaRegistry;
this._htmlParser = _htmlParser;
this._console = _console;
this.transforms = transforms;
}
/**
* @param {?} component
* @param {?} template
* @param {?} directives
* @param {?} pipes
* @param {?} schemas
* @param {?} templateUrl
* @return {?}
*/
TemplateParser.prototype.parse = function (component, template, directives, pipes, schemas, templateUrl) {
var /** @type {?} */ result = this.tryParse(component, template, directives, pipes, schemas, templateUrl);
var /** @type {?} */ warnings = ((result.errors)).filter(function (error) { return error.level === ParseErrorLevel.WARNING; })
.filter(warnOnlyOnce([TEMPLATE_ATTR_DEPRECATION_WARNING, TEMPLATE_ELEMENT_DEPRECATION_WARNING]));
var /** @type {?} */ errors = ((result.errors)).filter(function (error) { return error.level === ParseErrorLevel.ERROR; });
if (warnings.length > 0) {
this._console.warn("Template parse warnings:\n" + warnings.join('\n'));
}
if (errors.length > 0) {
var /** @type {?} */ errorString = errors.join('\n');
throw syntaxError("Template parse errors:\n" + errorString);
}
return { template: /** @type {?} */ ((result.templateAst)), pipes: /** @type {?} */ ((result.usedPipes)) };
};
/**
* @param {?} component
* @param {?} template
* @param {?} directives
* @param {?} pipes
* @param {?} schemas
* @param {?} templateUrl
* @return {?}
*/
TemplateParser.prototype.tryParse = function (component, template, directives, pipes, schemas, templateUrl) {
return this.tryParseHtml(this.expandHtml(/** @type {?} */ ((this._htmlParser)).parse(template, templateUrl, true, this.getInterpolationConfig(component))), component, directives, pipes, schemas);
};
/**
* @param {?} htmlAstWithErrors
* @param {?} component
* @param {?} directives
* @param {?} pipes
* @param {?} schemas
* @return {?}
*/
TemplateParser.prototype.tryParseHtml = function (htmlAstWithErrors, component, directives, pipes, schemas) {
var /** @type {?} */ result;
var /** @type {?} */ errors = htmlAstWithErrors.errors;
var /** @type {?} */ usedPipes = [];
if (htmlAstWithErrors.rootNodes.length > 0) {
var /** @type {?} */ uniqDirectives = removeSummaryDuplicates(directives);
var /** @type {?} */ uniqPipes = removeSummaryDuplicates(pipes);
var /** @type {?} */ providerViewContext = new ProviderViewContext(component);
var /** @type {?} */ interpolationConfig = ((undefined));
if (component.template && component.template.interpolation) {
interpolationConfig = {
start: component.template.interpolation[0],
end: component.template.interpolation[1]
};
}
var /** @type {?} */ bindingParser = new BindingParser(this._exprParser, /** @type {?} */ ((interpolationConfig)), this._schemaRegistry, uniqPipes, errors);
var /** @type {?} */ parseVisitor = new TemplateParseVisitor(this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors);
result = visitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
errors.push.apply(errors, providerViewContext.errors);
usedPipes.push.apply(usedPipes, bindingParser.getUsedPipes());
}
else {
result = [];
}
this._assertNoReferenceDuplicationOnTemplate(result, errors);
if (errors.length > 0) {
return new TemplateParseResult(result, usedPipes, errors);
}
if (this.transforms) {
this.transforms.forEach(function (transform) { result = templateVisitAll(transform, result); });
}
return new TemplateParseResult(result, usedPipes, errors);
};
/**
* @param {?} htmlAstWithErrors
* @param {?=} forced
* @return {?}
*/
TemplateParser.prototype.expandHtml = function (htmlAstWithErrors, forced) {
if (forced === void 0) { forced = false; }
var /** @type {?} */ errors = htmlAstWithErrors.errors;
if (errors.length == 0 || forced) {
// Transform ICU messages to angular directives
var /** @type {?} */ expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
errors.push.apply(errors, expandedHtmlAst.errors);
htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
}
return htmlAstWithErrors;
};
/**
* @param {?} component
* @return {?}
*/
TemplateParser.prototype.getInterpolationConfig = function (component) {
if (component.template) {
return InterpolationConfig.fromArray(component.template.interpolation);
}
return undefined;
};
/**
* \@internal
* @param {?} result
* @param {?} errors
* @return {?}
*/
TemplateParser.prototype._assertNoReferenceDuplicationOnTemplate = function (result, errors) {
var /** @type {?} */ existingReferences = [];
result.filter(function (element) { return !!((element)).references; })
.forEach(function (element) { return ((element)).references.forEach(function (reference) {
var /** @type {?} */ name = reference.name;
if (existingReferences.indexOf(name) < 0) {
existingReferences.push(name);
}
else {
var /** @type {?} */ error = new TemplateParseError("Reference \"#" + name + "\" is defined several times", reference.sourceSpan, ParseErrorLevel.ERROR);
errors.push(error);
}
}); });
};
return TemplateParser;
}());
TemplateParser.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
TemplateParser.ctorParameters = function () { return [
{ type: CompilerConfig, },
{ type: Parser, },
{ type: ElementSchemaRegistry, },
{ type: I18NHtmlParser, },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_47" /* ɵConsole */], },
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [TEMPLATE_TRANSFORMS,] },] },
]; };
var TemplateParseVisitor = (function () {
/**
* @param {?} config
* @param {?} providerViewContext
* @param {?} directives
* @param {?} _bindingParser
* @param {?} _schemaRegistry
* @param {?} _schemas
* @param {?} _targetErrors
*/
function TemplateParseVisitor(config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) {
var _this = this;
this.config = config;
this.providerViewContext = providerViewContext;
this._bindingParser = _bindingParser;
this._schemaRegistry = _schemaRegistry;
this._schemas = _schemas;
this._targetErrors = _targetErrors;
this.selectorMatcher = new SelectorMatcher();
this.directivesIndex = new Map();
this.ngContentCount = 0;
// Note: queries start with id 1 so we can use the number in a Bloom filter!
this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
directives.forEach(function (directive, index) {
var selector = CssSelector.parse(directive.selector);
_this.selectorMatcher.addSelectables(selector, directive);
_this.directivesIndex.set(directive, index);
});
}
/**
* @param {?} expansion
* @param {?} context
* @return {?}
*/
TemplateParseVisitor.prototype.visitExpansion = function (expansion, context) { return null; };
/**
* @param {?} expansionCase
* @param {?} context
* @return {?}
*/
TemplateParseVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return null; };
/**
* @param {?} text
* @param {?} parent
* @return {?}
*/
TemplateParseVisitor.prototype.visitText = function (text, parent) {
var /** @type {?} */ ngContentIndex = ((parent.findNgContentIndex(TEXT_CSS_SELECTOR)));
var /** @type {?} */ expr = this._bindingParser.parseInterpolation(text.value, /** @type {?} */ ((text.sourceSpan)));
return expr ? new BoundTextAst(expr, ngContentIndex, /** @type {?} */ ((text.sourceSpan))) :
new TextAst(text.value, ngContentIndex, /** @type {?} */ ((text.sourceSpan)));
};
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
TemplateParseVisitor.prototype.visitAttribute = function (attribute, context) {
return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
};
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
TemplateParseVisitor.prototype.visitComment = function (comment, context) { return null; };
/**
* @param {?} element
* @param {?} parent
* @return {?}
*/
TemplateParseVisitor.prototype.visitElement = function (element, parent) {
var _this = this;
var /** @type {?} */ queryStartIndex = this.contentQueryStartId;
var /** @type {?} */ nodeName = element.name;
var /** @type {?} */ preparsedElement = preparseElement(element);
if (preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE) {
// Skipping <script> for security reasons
// Skipping <style> as we already processed them
// in the StyleCompiler
return null;
}
if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
isStyleUrlResolvable(preparsedElement.hrefAttr)) {
// Skipping stylesheets with either relative urls or package scheme as we already processed
// them in the StyleCompiler
return null;
}
var /** @type {?} */ matchableAttrs = [];
var /** @type {?} */ elementOrDirectiveProps = [];
var /** @type {?} */ elementOrDirectiveRefs = [];
var /** @type {?} */ elementVars = [];
var /** @type {?} */ events = [];
var /** @type {?} */ templateElementOrDirectiveProps = [];
var /** @type {?} */ templateMatchableAttrs = [];
var /** @type {?} */ templateElementVars = [];
var /** @type {?} */ hasInlineTemplates = false;
var /** @type {?} */ attrs = [];
var /** @type {?} */ isTemplateElement = isTemplate(element, this.config.enableLegacyTemplate, function (m, span) { return _this._reportError(m, span, ParseErrorLevel.WARNING); });
element.attrs.forEach(function (attr) {
var /** @type {?} */ hasBinding = _this._parseAttr(isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events, elementOrDirectiveRefs, elementVars);
var /** @type {?} */ templateBindingsSource;
var /** @type {?} */ prefixToken;
var /** @type {?} */ normalizedName = _this._normalizeAttributeName(attr.name);
if (_this.config.enableLegacyTemplate && normalizedName == TEMPLATE_ATTR) {
_this._reportError(TEMPLATE_ATTR_DEPRECATION_WARNING, attr.sourceSpan, ParseErrorLevel.WARNING);
templateBindingsSource = attr.value;
}
else if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
templateBindingsSource = attr.value;
prefixToken = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length) + ':';
}
var /** @type {?} */ hasTemplateBinding = templateBindingsSource != null;
if (hasTemplateBinding) {
if (hasInlineTemplates) {
_this._reportError("Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *", attr.sourceSpan);
}
hasInlineTemplates = true;
_this._bindingParser.parseInlineTemplateBinding(/** @type {?} */ ((prefixToken)), /** @type {?} */ ((templateBindingsSource)), attr.sourceSpan, templateMatchableAttrs, templateElementOrDirectiveProps, templateElementVars);
}
if (!hasBinding && !hasTemplateBinding) {
// don't include the bindings as attributes as well in the AST
attrs.push(_this.visitAttribute(attr, null));
matchableAttrs.push([attr.name, attr.value]);
}
});
var /** @type {?} */ elementCssSelector = createElementCssSelector(nodeName, matchableAttrs);
var _a = this._parseDirectives(this.selectorMatcher, elementCssSelector), directiveMetas = _a.directives, matchElement = _a.matchElement;
var /** @type {?} */ references = [];
var /** @type {?} */ boundDirectivePropNames = new Set();
var /** @type {?} */ directiveAsts = this._createDirectiveAsts(isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, /** @type {?} */ ((element.sourceSpan)), references, boundDirectivePropNames);
var /** @type {?} */ elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, boundDirectivePropNames);
var /** @type {?} */ isViewRoot = parent.isTemplateElement || hasInlineTemplates;
var /** @type {?} */ providerContext = new ProviderElementContext(this.providerViewContext, /** @type {?} */ ((parent.providerContext)), isViewRoot, directiveAsts, attrs, references, isTemplateElement, queryStartIndex, /** @type {?} */ ((element.sourceSpan)));
var /** @type {?} */ children = visitAll(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create(isTemplateElement, directiveAsts, isTemplateElement ? ((parent.providerContext)) : providerContext));
providerContext.afterElement();
// Override the actual selector when the `ngProjectAs` attribute is provided
var /** @type {?} */ projectionSelector = preparsedElement.projectAs != null ?
CssSelector.parse(preparsedElement.projectAs)[0] :
elementCssSelector;
var /** @type {?} */ ngContentIndex = ((parent.findNgContentIndex(projectionSelector)));
var /** @type {?} */ parsedElement;
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
if (element.children && !element.children.every(_isEmptyTextNode)) {
this._reportError("<ng-content> element cannot have content.", /** @type {?} */ ((element.sourceSpan)));
}
parsedElement = new NgContentAst(this.ngContentCount++, hasInlineTemplates ? ((null)) : ngContentIndex, /** @type {?} */ ((element.sourceSpan)));
}
else if (isTemplateElement) {
this._assertAllEventsPublishedByDirectives(directiveAsts, events);
this._assertNoComponentsNorElementBindingsOnTemplate(directiveAsts, elementProps, /** @type {?} */ ((element.sourceSpan)));
parsedElement = new EmbeddedTemplateAst(attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? ((null)) : ngContentIndex, /** @type {?} */ ((element.sourceSpan)));
}
else {
this._assertElementExists(matchElement, element);
this._assertOnlyOneComponent(directiveAsts, /** @type {?} */ ((element.sourceSpan)));
var /** @type {?} */ ngContentIndex_1 = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
parsedElement = new ElementAst(nodeName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex_1, element.sourceSpan, element.endSourceSpan || null);
}
if (hasInlineTemplates) {
var /** @type {?} */ templateQueryStartIndex = this.contentQueryStartId;
var /** @type {?} */ templateSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs);
var templateDirectiveMetas = this._parseDirectives(this.selectorMatcher, templateSelector).directives;
var /** @type {?} */ templateBoundDirectivePropNames = new Set();
var /** @type {?} */ templateDirectiveAsts = this._createDirectiveAsts(true, element.name, templateDirectiveMetas, templateElementOrDirectiveProps, [], /** @type {?} */ ((element.sourceSpan)), [], templateBoundDirectivePropNames);
var /** @type {?} */ templateElementProps = this._createElementPropertyAsts(element.name, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectiveAsts, templateElementProps, /** @type {?} */ ((element.sourceSpan)));
var /** @type {?} */ templateProviderContext = new ProviderElementContext(this.providerViewContext, /** @type {?} */ ((parent.providerContext)), parent.isTemplateElement, templateDirectiveAsts, [], [], true, templateQueryStartIndex, /** @type {?} */ ((element.sourceSpan)));
templateProviderContext.afterElement();
parsedElement = new EmbeddedTemplateAst([], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches, [parsedElement], ngContentIndex, /** @type {?} */ ((element.sourceSpan)));
}
return parsedElement;
};
/**
* @param {?} isTemplateElement
* @param {?} attr
* @param {?} targetMatchableAttrs
* @param {?} targetProps
* @param {?} targetEvents
* @param {?} targetRefs
* @param {?} targetVars
* @return {?}
*/
TemplateParseVisitor.prototype._parseAttr = function (isTemplateElement, attr, targetMatchableAttrs, targetProps, targetEvents, targetRefs, targetVars) {
var /** @type {?} */ name = this._normalizeAttributeName(attr.name);
var /** @type {?} */ value = attr.value;
var /** @type {?} */ srcSpan = attr.sourceSpan;
var /** @type {?} */ bindParts = name.match(BIND_NAME_REGEXP);
var /** @type {?} */ hasBinding = false;
if (bindParts !== null) {
hasBinding = true;
if (bindParts[KW_BIND_IDX] != null) {
this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
}
else if (bindParts[KW_LET_IDX]) {
if (isTemplateElement) {
var /** @type {?} */ identifier = bindParts[IDENT_KW_IDX];
this._parseVariable(identifier, value, srcSpan, targetVars);
}
else {
this._reportError("\"let-\" is only supported on template elements.", srcSpan);
}
}
else if (bindParts[KW_REF_IDX]) {
var /** @type {?} */ identifier = bindParts[IDENT_KW_IDX];
this._parseReference(identifier, value, srcSpan, targetRefs);
}
else if (bindParts[KW_ON_IDX]) {
this._bindingParser.parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, targetMatchableAttrs, targetEvents);
}
else if (bindParts[KW_BINDON_IDX]) {
this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, targetMatchableAttrs, targetEvents);
}
else if (bindParts[KW_AT_IDX]) {
this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
}
else if (bindParts[IDENT_BANANA_BOX_IDX]) {
this._bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
this._parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, targetMatchableAttrs, targetEvents);
}
else if (bindParts[IDENT_PROPERTY_IDX]) {
this._bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
}
else if (bindParts[IDENT_EVENT_IDX]) {
this._bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, targetMatchableAttrs, targetEvents);
}
}
else {
hasBinding = this._bindingParser.parsePropertyInterpolation(name, value, srcSpan, targetMatchableAttrs, targetProps);
}
if (!hasBinding) {
this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
}
return hasBinding;
};
/**
* @param {?} attrName
* @return {?}
*/
TemplateParseVisitor.prototype._normalizeAttributeName = function (attrName) {
return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
};
/**
* @param {?} identifier
* @param {?} value
* @param {?} sourceSpan
* @param {?} targetVars
* @return {?}
*/
TemplateParseVisitor.prototype._parseVariable = function (identifier, value, sourceSpan, targetVars) {
if (identifier.indexOf('-') > -1) {
this._reportError("\"-\" is not allowed in variable names", sourceSpan);
}
targetVars.push(new VariableAst(identifier, value, sourceSpan));
};
/**
* @param {?} identifier
* @param {?} value
* @param {?} sourceSpan
* @param {?} targetRefs
* @return {?}
*/
TemplateParseVisitor.prototype._parseReference = function (identifier, value, sourceSpan, targetRefs) {
if (identifier.indexOf('-') > -1) {
this._reportError("\"-\" is not allowed in reference names", sourceSpan);
}
targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
};
/**
* @param {?} name
* @param {?} expression
* @param {?} sourceSpan
* @param {?} targetMatchableAttrs
* @param {?} targetEvents
* @return {?}
*/
TemplateParseVisitor.prototype._parseAssignmentEvent = function (name, expression, sourceSpan, targetMatchableAttrs, targetEvents) {
this._bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, targetMatchableAttrs, targetEvents);
};
/**
* @param {?} selectorMatcher
* @param {?} elementCssSelector
* @return {?}
*/
TemplateParseVisitor.prototype._parseDirectives = function (selectorMatcher, elementCssSelector) {
var _this = this;
// Need to sort the directives so that we get consistent results throughout,
// as selectorMatcher uses Maps inside.
// Also deduplicate directives as they might match more than one time!
var /** @type {?} */ directives = new Array(this.directivesIndex.size);
// Whether any directive selector matches on the element name
var /** @type {?} */ matchElement = false;
selectorMatcher.match(elementCssSelector, function (selector, directive) {
directives[((_this.directivesIndex.get(directive)))] = directive;
matchElement = matchElement || selector.hasElementSelector();
});
return {
directives: directives.filter(function (dir) { return !!dir; }),
matchElement: matchElement,
};
};
/**
* @param {?} isTemplateElement
* @param {?} elementName
* @param {?} directives
* @param {?} props
* @param {?} elementOrDirectiveRefs
* @param {?} elementSourceSpan
* @param {?} targetReferences
* @param {?} targetBoundDirectivePropNames
* @return {?}
*/
TemplateParseVisitor.prototype._createDirectiveAsts = function (isTemplateElement, elementName, directives, props, elementOrDirectiveRefs, elementSourceSpan, targetReferences, targetBoundDirectivePropNames) {
var _this = this;
var /** @type {?} */ matchedReferences = new Set();
var /** @type {?} */ component = ((null));
var /** @type {?} */ directiveAsts = directives.map(function (directive) {
var /** @type {?} */ sourceSpan = new ParseSourceSpan(elementSourceSpan.start, elementSourceSpan.end, "Directive " + identifierName(directive.type));
if (directive.isComponent) {
component = directive;
}
var /** @type {?} */ directiveProperties = [];
var /** @type {?} */ hostProperties = ((_this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan)));
// Note: We need to check the host properties here as well,
// as we don't know the element name in the DirectiveWrapperCompiler yet.
hostProperties = _this._checkPropertiesInSchema(elementName, hostProperties);
var /** @type {?} */ hostEvents = ((_this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan)));
_this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
elementOrDirectiveRefs.forEach(function (elOrDirRef) {
if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
(directive.exportAs == elOrDirRef.value)) {
targetReferences.push(new ReferenceAst(elOrDirRef.name, identifierToken(directive.type), elOrDirRef.sourceSpan));
matchedReferences.add(elOrDirRef.name);
}
});
var /** @type {?} */ contentQueryStartId = _this.contentQueryStartId;
_this.contentQueryStartId += directive.queries.length;
return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId, sourceSpan);
});
elementOrDirectiveRefs.forEach(function (elOrDirRef) {
if (elOrDirRef.value.length > 0) {
if (!matchedReferences.has(elOrDirRef.name)) {
_this._reportError("There is no directive with \"exportAs\" set to \"" + elOrDirRef.value + "\"", elOrDirRef.sourceSpan);
}
}
else if (!component) {
var /** @type {?} */ refToken = ((null));
if (isTemplateElement) {
refToken = createIdentifierToken(Identifiers.TemplateRef);
}
targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.sourceSpan));
}
});
return directiveAsts;
};
/**
* @param {?} directiveProperties
* @param {?} boundProps
* @param {?} targetBoundDirectiveProps
* @param {?} targetBoundDirectivePropNames
* @return {?}
*/
TemplateParseVisitor.prototype._createDirectivePropertyAsts = function (directiveProperties, boundProps, targetBoundDirectiveProps, targetBoundDirectivePropNames) {
if (directiveProperties) {
var /** @type {?} */ boundPropsByName_1 = new Map();
boundProps.forEach(function (boundProp) {
var /** @type {?} */ prevValue = boundPropsByName_1.get(boundProp.name);
if (!prevValue || prevValue.isLiteral) {
// give [a]="b" a higher precedence than a="b" on the same element
boundPropsByName_1.set(boundProp.name, boundProp);
}
});
Object.keys(directiveProperties).forEach(function (dirProp) {
var /** @type {?} */ elProp = directiveProperties[dirProp];
var /** @type {?} */ boundProp = boundPropsByName_1.get(elProp);
// Bindings are optional, so this binding only needs to be set up if an expression is given.
if (boundProp) {
targetBoundDirectivePropNames.add(boundProp.name);
if (!isEmptyExpression(boundProp.expression)) {
targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
}
}
});
}
};
/**
* @param {?} elementName
* @param {?} props
* @param {?} boundDirectivePropNames
* @return {?}
*/
TemplateParseVisitor.prototype._createElementPropertyAsts = function (elementName, props, boundDirectivePropNames) {
var _this = this;
var /** @type {?} */ boundElementProps = [];
props.forEach(function (prop) {
if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
boundElementProps.push(_this._bindingParser.createElementPropertyAst(elementName, prop));
}
});
return this._checkPropertiesInSchema(elementName, boundElementProps);
};
/**
* @param {?} directives
* @return {?}
*/
TemplateParseVisitor.prototype._findComponentDirectives = function (directives) {
return directives.filter(function (directive) { return directive.directive.isComponent; });
};
/**
* @param {?} directives
* @return {?}
*/
TemplateParseVisitor.prototype._findComponentDirectiveNames = function (directives) {
return this._findComponentDirectives(directives)
.map(function (directive) { return ((identifierName(directive.directive.type))); });
};
/**
* @param {?} directives
* @param {?} sourceSpan
* @return {?}
*/
TemplateParseVisitor.prototype._assertOnlyOneComponent = function (directives, sourceSpan) {
var /** @type {?} */ componentTypeNames = this._findComponentDirectiveNames(directives);
if (componentTypeNames.length > 1) {
this._reportError("More than one component matched on this element.\n" +
"Make sure that only one component's selector can match a given element.\n" +
("Conflicting components: " + componentTypeNames.join(',')), sourceSpan);
}
};
/**
* Make sure that non-angular tags conform to the schemas.
*
* Note: An element is considered an angular tag when at least one directive selector matches the
* tag name.
*
* @param {?} matchElement Whether any directive has matched on the tag name
* @param {?} element the html element
* @return {?}
*/
TemplateParseVisitor.prototype._assertElementExists = function (matchElement, element) {
var /** @type {?} */ elName = element.name.replace(/^:xhtml:/, '');
if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
var /** @type {?} */ errorMsg = "'" + elName + "' is not a known element:\n";
errorMsg +=
"1. If '" + elName + "' is an Angular component, then verify that it is part of this module.\n";
if (elName.indexOf('-') > -1) {
errorMsg +=
"2. If '" + elName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.";
}
else {
errorMsg +=
"2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
}
this._reportError(errorMsg, /** @type {?} */ ((element.sourceSpan)));
}
};
/**
* @param {?} directives
* @param {?} elementProps
* @param {?} sourceSpan
* @return {?}
*/
TemplateParseVisitor.prototype._assertNoComponentsNorElementBindingsOnTemplate = function (directives, elementProps, sourceSpan) {
var _this = this;
var /** @type {?} */ componentTypeNames = this._findComponentDirectiveNames(directives);
if (componentTypeNames.length > 0) {
this._reportError("Components on an embedded template: " + componentTypeNames.join(','), sourceSpan);
}
elementProps.forEach(function (prop) {
_this._reportError("Property binding " + prop.name + " not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the \"@NgModule.declarations\".", sourceSpan);
});
};
/**
* @param {?} directives
* @param {?} events
* @return {?}
*/
TemplateParseVisitor.prototype._assertAllEventsPublishedByDirectives = function (directives, events) {
var _this = this;
var /** @type {?} */ allDirectiveEvents = new Set();
directives.forEach(function (directive) {
Object.keys(directive.directive.outputs).forEach(function (k) {
var /** @type {?} */ eventName = directive.directive.outputs[k];
allDirectiveEvents.add(eventName);
});
});
events.forEach(function (event) {
if (event.target != null || !allDirectiveEvents.has(event.name)) {
_this._reportError("Event binding " + event.fullName + " not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the \"@NgModule.declarations\".", event.sourceSpan);
}
});
};
/**
* @param {?} elementName
* @param {?} boundProps
* @return {?}
*/
TemplateParseVisitor.prototype._checkPropertiesInSchema = function (elementName, boundProps) {
var _this = this;
// Note: We can't filter out empty expressions before this method,
// as we still want to validate them!
return boundProps.filter(function (boundProp) {
if (boundProp.type === PropertyBindingType.Property &&
!_this._schemaRegistry.hasProperty(elementName, boundProp.name, _this._schemas)) {
var /** @type {?} */ errorMsg = "Can't bind to '" + boundProp.name + "' since it isn't a known property of '" + elementName + "'.";
if (elementName.startsWith('ng-')) {
errorMsg +=
"\n1. If '" + boundProp.name + "' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component." +
"\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
}
else if (elementName.indexOf('-') > -1) {
errorMsg +=
"\n1. If '" + elementName + "' is an Angular component and it has '" + boundProp.name + "' input, then verify that it is part of this module." +
("\n2. If '" + elementName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.") +
"\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
}
_this._reportError(errorMsg, boundProp.sourceSpan);
}
return !isEmptyExpression(boundProp.value);
});
};
/**
* @param {?} message
* @param {?} sourceSpan
* @param {?=} level
* @return {?}
*/
TemplateParseVisitor.prototype._reportError = function (message, sourceSpan, level) {
if (level === void 0) { level = ParseErrorLevel.ERROR; }
this._targetErrors.push(new ParseError(sourceSpan, message, level));
};
return TemplateParseVisitor;
}());
var NonBindableVisitor = (function () {
function NonBindableVisitor() {
}
/**
* @param {?} ast
* @param {?} parent
* @return {?}
*/
NonBindableVisitor.prototype.visitElement = function (ast, parent) {
var /** @type {?} */ preparsedElement = preparseElement(ast);
if (preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE ||
preparsedElement.type === PreparsedElementType.STYLESHEET) {
// Skipping <script> for security reasons
// Skipping <style> and stylesheets as we already processed them
// in the StyleCompiler
return null;
}
var /** @type {?} */ attrNameAndValues = ast.attrs.map(function (attr) { return [attr.name, attr.value]; });
var /** @type {?} */ selector = createElementCssSelector(ast.name, attrNameAndValues);
var /** @type {?} */ ngContentIndex = parent.findNgContentIndex(selector);
var /** @type {?} */ children = visitAll(this, ast.children, EMPTY_ELEMENT_CONTEXT);
return new ElementAst(ast.name, visitAll(this, ast.attrs), [], [], [], [], [], false, [], children, ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
};
/**
* @param {?} comment
* @param {?} context
* @return {?}
*/
NonBindableVisitor.prototype.visitComment = function (comment, context) { return null; };
/**
* @param {?} attribute
* @param {?} context
* @return {?}
*/
NonBindableVisitor.prototype.visitAttribute = function (attribute, context) {
return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
};
/**
* @param {?} text
* @param {?} parent
* @return {?}
*/
NonBindableVisitor.prototype.visitText = function (text, parent) {
var /** @type {?} */ ngContentIndex = ((parent.findNgContentIndex(TEXT_CSS_SELECTOR)));
return new TextAst(text.value, ngContentIndex, /** @type {?} */ ((text.sourceSpan)));
};
/**
* @param {?} expansion
* @param {?} context
* @return {?}
*/
NonBindableVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
/**
* @param {?} expansionCase
* @param {?} context
* @return {?}
*/
NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
return NonBindableVisitor;
}());
var ElementOrDirectiveRef = (function () {
/**
* @param {?} name
* @param {?} value
* @param {?} sourceSpan
*/
function ElementOrDirectiveRef(name, value, sourceSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
}
return ElementOrDirectiveRef;
}());
/**
* @param {?} classAttrValue
* @return {?}
*/
function splitClasses(classAttrValue) {
return classAttrValue.trim().split(/\s+/g);
}
var ElementContext = (function () {
/**
* @param {?} isTemplateElement
* @param {?} _ngContentIndexMatcher
* @param {?} _wildcardNgContentIndex
* @param {?} providerContext
*/
function ElementContext(isTemplateElement, _ngContentIndexMatcher, _wildcardNgContentIndex, providerContext) {
this.isTemplateElement = isTemplateElement;
this._ngContentIndexMatcher = _ngContentIndexMatcher;
this._wildcardNgContentIndex = _wildcardNgContentIndex;
this.providerContext = providerContext;
}
/**
* @param {?} isTemplateElement
* @param {?} directives
* @param {?} providerContext
* @return {?}
*/
ElementContext.create = function (isTemplateElement, directives, providerContext) {
var /** @type {?} */ matcher = new SelectorMatcher();
var /** @type {?} */ wildcardNgContentIndex = ((null));
var /** @type {?} */ component = directives.find(function (directive) { return directive.directive.isComponent; });
if (component) {
var /** @type {?} */ ngContentSelectors = ((component.directive.template)).ngContentSelectors;
for (var /** @type {?} */ i = 0; i < ngContentSelectors.length; i++) {
var /** @type {?} */ selector = ngContentSelectors[i];
if (selector === '*') {
wildcardNgContentIndex = i;
}
else {
matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
}
}
}
return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
};
/**
* @param {?} selector
* @return {?}
*/
ElementContext.prototype.findNgContentIndex = function (selector) {
var /** @type {?} */ ngContentIndices = [];
this._ngContentIndexMatcher.match(selector, function (selector, ngContentIndex) { ngContentIndices.push(ngContentIndex); });
ngContentIndices.sort();
if (this._wildcardNgContentIndex != null) {
ngContentIndices.push(this._wildcardNgContentIndex);
}
return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
};
return ElementContext;
}());
/**
* @param {?} elementName
* @param {?} attributes
* @return {?}
*/
function createElementCssSelector(elementName, attributes) {
var /** @type {?} */ cssSelector = new CssSelector();
var /** @type {?} */ elNameNoNs = splitNsName(elementName)[1];
cssSelector.setElement(elNameNoNs);
for (var /** @type {?} */ i = 0; i < attributes.length; i++) {
var /** @type {?} */ attrName = attributes[i][0];
var /** @type {?} */ attrNameNoNs = splitNsName(attrName)[1];
var /** @type {?} */ attrValue = attributes[i][1];
cssSelector.addAttribute(attrNameNoNs, attrValue);
if (attrName.toLowerCase() == CLASS_ATTR) {
var /** @type {?} */ classes = splitClasses(attrValue);
classes.forEach(function (className) { return cssSelector.addClassName(className); });
}
}
return cssSelector;
}
var EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
var NON_BINDABLE_VISITOR = new NonBindableVisitor();
/**
* @param {?} node
* @return {?}
*/
function _isEmptyTextNode(node) {
return node instanceof Text && node.value.trim().length == 0;
}
/**
* @template T
* @param {?} items
* @return {?}
*/
function removeSummaryDuplicates(items) {
var /** @type {?} */ map = new Map();
items.forEach(function (item) {
if (!map.get(item.type.reference)) {
map.set(item.type.reference, item);
}
});
return Array.from(map.values());
}
/**
* @param {?} ast
* @return {?}
*/
function isEmptyExpression(ast) {
if (ast instanceof ASTWithSource) {
ast = ast.ast;
}
return ast instanceof EmptyExpr;
}
/**
* @param {?} el
* @param {?} enableLegacyTemplate
* @param {?} reportDeprecation
* @return {?}
*/
function isTemplate(el, enableLegacyTemplate, reportDeprecation) {
if (isNgTemplate(el.name))
return true;
var /** @type {?} */ tagNoNs = splitNsName(el.name)[1];
// `<template>` is HTML and case insensitive
if (tagNoNs.toLowerCase() === TEMPLATE_ELEMENT) {
if (enableLegacyTemplate && tagNoNs.toLowerCase() === TEMPLATE_ELEMENT) {
reportDeprecation(TEMPLATE_ELEMENT_DEPRECATION_WARNING, /** @type {?} */ ((el.sourceSpan)));
return true;
}
}
return false;
}
/**
* An interface for retrieving documents by URL that the compiler uses
* to load templates.
*/
var ResourceLoader = (function () {
function ResourceLoader() {
}
/**
* @param {?} url
* @return {?}
*/
ResourceLoader.prototype.get = function (url) { return null; };
return ResourceLoader;
}());
/**
* @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
*/
/**
* Create a {\@link UrlResolver} with no package prefix.
* @return {?}
*/
function createUrlResolverWithoutPackagePrefix() {
return new UrlResolver();
}
/**
* @return {?}
*/
function createOfflineCompileUrlResolver() {
return new UrlResolver('.');
}
/**
* A default provider for {@link PACKAGE_ROOT_URL} that maps to '/'.
*/
var DEFAULT_PACKAGE_URL_PROVIDER = {
provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_48" /* PACKAGE_ROOT_URL */],
useValue: '/'
};
/**
* Used by the {\@link Compiler} when resolving HTML and CSS template URLs.
*
* This class can be overridden by the application developer to create custom behavior.
*
* See {\@link Compiler}
*
* ## Example
*
* {\@example compiler/ts/url_resolver/url_resolver.ts region='url_resolver'}
*
* \@security When compiling templates at runtime, you must
* ensure that the entire template comes from a trusted source.
* Attacker-controlled data introduced by a template could expose your
* application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
*/
var UrlResolver = (function () {
/**
* @param {?=} _packagePrefix
*/
function UrlResolver(_packagePrefix) {
if (_packagePrefix === void 0) { _packagePrefix = null; }
this._packagePrefix = _packagePrefix;
}
/**
* Resolves the `url` given the `baseUrl`:
* - when the `url` is null, the `baseUrl` is returned,
* - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
* `baseUrl` and `url`,
* - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
* returned as is (ignoring the `baseUrl`)
* @param {?} baseUrl
* @param {?} url
* @return {?}
*/
UrlResolver.prototype.resolve = function (baseUrl, url) {
var /** @type {?} */ resolvedUrl = url;
if (baseUrl != null && baseUrl.length > 0) {
resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
}
var /** @type {?} */ resolvedParts = _split(resolvedUrl);
var /** @type {?} */ prefix = this._packagePrefix;
if (prefix != null && resolvedParts != null &&
resolvedParts[_ComponentIndex.Scheme] == 'package') {
var /** @type {?} */ path = resolvedParts[_ComponentIndex.Path];
prefix = prefix.replace(/\/+$/, '');
path = path.replace(/^\/+/, '');
return prefix + "/" + path;
}
return resolvedUrl;
};
return UrlResolver;
}());
UrlResolver.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
UrlResolver.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [__WEBPACK_IMPORTED_MODULE_0__angular_core__["_48" /* PACKAGE_ROOT_URL */],] },] },
]; };
/**
* Extract the scheme of a URL.
* @param {?} url
* @return {?}
*/
function getUrlScheme(url) {
var /** @type {?} */ match = _split(url);
return (match && match[_ComponentIndex.Scheme]) || '';
}
/**
* Builds a URI string from already-encoded parts.
*
* No encoding is performed. Any component may be omitted as either null or
* undefined.
*
* @param {?=} opt_scheme The scheme such as 'http'.
* @param {?=} opt_userInfo The user name before the '\@'.
* @param {?=} opt_domain The domain such as 'www.google.com', already
* URI-encoded.
* @param {?=} opt_port The port number.
* @param {?=} opt_path The path, already URI-encoded. If it is not
* empty, it must begin with a slash.
* @param {?=} opt_queryData The URI-encoded query data.
* @param {?=} opt_fragment The URI-encoded fragment identifier.
* @return {?} The fully combined URI.
*/
function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var /** @type {?} */ out = [];
if (opt_scheme != null) {
out.push(opt_scheme + ':');
}
if (opt_domain != null) {
out.push('//');
if (opt_userInfo != null) {
out.push(opt_userInfo + '@');
}
out.push(opt_domain);
if (opt_port != null) {
out.push(':' + opt_port);
}
}
if (opt_path != null) {
out.push(opt_path);
}
if (opt_queryData != null) {
out.push('?' + opt_queryData);
}
if (opt_fragment != null) {
out.push('#' + opt_fragment);
}
return out.join('');
}
/**
* A regular expression for breaking a URI into its component parts.
*
* {\@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says
* As the "first-match-wins" algorithm is identical to the "greedy"
* disambiguation method used by POSIX regular expressions, it is natural and
* commonplace to use a regular expression for parsing the potential five
* components of a URI reference.
*
* The following line is the regular expression for breaking-down a
* well-formed URI reference into its components.
*
* <pre>
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
* 12 3 4 5 6 7 8 9
* </pre>
*
* The numbers in the second line above are only to assist readability; they
* indicate the reference points for each subexpression (i.e., each paired
* parenthesis). We refer to the value matched for subexpression <n> as $<n>.
* For example, matching the above expression to
* <pre>
* http://www.ics.uci.edu/pub/ietf/uri/#Related
* </pre>
* results in the following subexpression matches:
* <pre>
* $1 = http:
* $2 = http
* $3 = //www.ics.uci.edu
* $4 = www.ics.uci.edu
* $5 = /pub/ietf/uri/
* $6 = <undefined>
* $7 = <undefined>
* $8 = #Related
* $9 = Related
* </pre>
* where <undefined> indicates that the component is not present, as is the
* case for the query component in the above example. Therefore, we can
* determine the value of the five components as
* <pre>
* scheme = $2
* authority = $4
* path = $5
* query = $7
* fragment = $9
* </pre>
*
* The regular expression has been modified slightly to expose the
* userInfo, domain, and port separately from the authority.
* The modified version yields
* <pre>
* $1 = http scheme
* $2 = <undefined> userInfo -\
* $3 = www.ics.uci.edu domain | authority
* $4 = <undefined> port -/
* $5 = /pub/ietf/uri/ path
* $6 = <undefined> query without ?
* $7 = Related fragment without #
* </pre>
* \@internal
*/
var _splitRe = new RegExp('^' +
'(?:' +
'([^:/?#.]+)' +
// used by other URL parts such as :,
// ?, /, #, and .
':)?' +
'(?://' +
'(?:([^/?#]*)@)?' +
'([\\w\\d\\-\\u0100-\\uffff.%]*)' +
// digits, dashes, dots, percent
// escapes, and unicode characters.
'(?::([0-9]+))?' +
')?' +
'([^?#]+)?' +
'(?:\\?([^#]*))?' +
'(?:#(.*))?' +
'$');
var _ComponentIndex = {};
_ComponentIndex.Scheme = 1;
_ComponentIndex.UserInfo = 2;
_ComponentIndex.Domain = 3;
_ComponentIndex.Port = 4;
_ComponentIndex.Path = 5;
_ComponentIndex.QueryData = 6;
_ComponentIndex.Fragment = 7;
_ComponentIndex[_ComponentIndex.Scheme] = "Scheme";
_ComponentIndex[_ComponentIndex.UserInfo] = "UserInfo";
_ComponentIndex[_ComponentIndex.Domain] = "Domain";
_ComponentIndex[_ComponentIndex.Port] = "Port";
_ComponentIndex[_ComponentIndex.Path] = "Path";
_ComponentIndex[_ComponentIndex.QueryData] = "QueryData";
_ComponentIndex[_ComponentIndex.Fragment] = "Fragment";
/**
* Splits a URI into its component parts.
*
* Each component can be accessed via the component indices; for example:
* <pre>
* goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
* </pre>
*
* @param {?} uri The URI string to examine.
* @return {?} Each component still URI-encoded.
* Each component that is present will contain the encoded value, whereas
* components that are not present will be undefined or empty, depending
* on the browser's regular expression implementation. Never null, since
* arbitrary strings may still look like path names.
*/
function _split(uri) {
return ((uri.match(_splitRe)));
}
/**
* Removes dot segments in given path component, as described in
* RFC 3986, section 5.2.4.
*
* @param {?} path A non-empty path component.
* @return {?} Path component with removed dot segments.
*/
function _removeDotSegments(path) {
if (path == '/')
return '/';
var /** @type {?} */ leadingSlash = path[0] == '/' ? '/' : '';
var /** @type {?} */ trailingSlash = path[path.length - 1] === '/' ? '/' : '';
var /** @type {?} */ segments = path.split('/');
var /** @type {?} */ out = [];
var /** @type {?} */ up = 0;
for (var /** @type {?} */ pos = 0; pos < segments.length; pos++) {
var /** @type {?} */ segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length > 0) {
out.pop();
}
else {
up++;
}
break;
default:
out.push(segment);
}
}
if (leadingSlash == '') {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
/**
* Takes an array of the parts from split and canonicalizes the path part
* and then joins all the parts.
* @param {?} parts
* @return {?}
*/
function _joinAndCanonicalizePath(parts) {
var /** @type {?} */ path = parts[_ComponentIndex.Path];
path = path == null ? '' : _removeDotSegments(path);
parts[_ComponentIndex.Path] = path;
return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
}
/**
* Resolves a URL.
* @param {?} base The URL acting as the base URL.
* @param {?} url
* @return {?}
*/
function _resolveUrl(base, url) {
var /** @type {?} */ parts = _split(encodeURI(url));
var /** @type {?} */ baseParts = _split(base);
if (parts[_ComponentIndex.Scheme] != null) {
return _joinAndCanonicalizePath(parts);
}
else {
parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
}
for (var /** @type {?} */ i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
if (parts[i] == null) {
parts[i] = baseParts[i];
}
}
if (parts[_ComponentIndex.Path][0] == '/') {
return _joinAndCanonicalizePath(parts);
}
var /** @type {?} */ path = baseParts[_ComponentIndex.Path];
if (path == null)
path = '/';
var /** @type {?} */ index = path.lastIndexOf('/');
path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
parts[_ComponentIndex.Path] = path;
return _joinAndCanonicalizePath(parts);
}
/**
* @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
*/
var DirectiveNormalizer = (function () {
/**
* @param {?} _resourceLoader
* @param {?} _urlResolver
* @param {?} _htmlParser
* @param {?} _config
*/
function DirectiveNormalizer(_resourceLoader, _urlResolver, _htmlParser, _config) {
this._resourceLoader = _resourceLoader;
this._urlResolver = _urlResolver;
this._htmlParser = _htmlParser;
this._config = _config;
this._resourceLoaderCache = new Map();
}
/**
* @return {?}
*/
DirectiveNormalizer.prototype.clearCache = function () { this._resourceLoaderCache.clear(); };
/**
* @param {?} normalizedDirective
* @return {?}
*/
DirectiveNormalizer.prototype.clearCacheFor = function (normalizedDirective) {
var _this = this;
if (!normalizedDirective.isComponent) {
return;
}
var /** @type {?} */ template = ((normalizedDirective.template));
this._resourceLoaderCache.delete(/** @type {?} */ ((template.templateUrl)));
template.externalStylesheets.forEach(function (stylesheet) { _this._resourceLoaderCache.delete(/** @type {?} */ ((stylesheet.moduleUrl))); });
};
/**
* @param {?} url
* @return {?}
*/
DirectiveNormalizer.prototype._fetch = function (url) {
var /** @type {?} */ result = this._resourceLoaderCache.get(url);
if (!result) {
result = ((this._resourceLoader.get(url)));
this._resourceLoaderCache.set(url, result);
}
return result;
};
/**
* @param {?} prenormData
* @return {?}
*/
DirectiveNormalizer.prototype.normalizeTemplate = function (prenormData) {
var _this = this;
var /** @type {?} */ normalizedTemplateSync = ((null));
var /** @type {?} */ normalizedTemplateAsync = ((undefined));
if (isDefined(prenormData.template)) {
if (isDefined(prenormData.templateUrl)) {
throw syntaxError("'" + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(prenormData.componentType) + "' component cannot define both template and templateUrl");
}
if (typeof prenormData.template !== 'string') {
throw syntaxError("The template specified for component " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(prenormData.componentType) + " is not a string");
}
normalizedTemplateSync = this.normalizeTemplateSync(prenormData);
normalizedTemplateAsync = Promise.resolve(/** @type {?} */ ((normalizedTemplateSync)));
}
else if (isDefined(prenormData.templateUrl)) {
if (typeof prenormData.templateUrl !== 'string') {
throw syntaxError("The templateUrl specified for component " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(prenormData.componentType) + " is not a string");
}
normalizedTemplateAsync = this.normalizeTemplateAsync(prenormData);
}
else {
throw syntaxError("No template specified for component " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(prenormData.componentType));
}
if (normalizedTemplateSync && normalizedTemplateSync.styleUrls.length === 0) {
// sync case
return new SyncAsyncResult(normalizedTemplateSync);
}
else {
// async case
return new SyncAsyncResult(null, normalizedTemplateAsync.then(function (normalizedTemplate) { return _this.normalizeExternalStylesheets(normalizedTemplate); }));
}
};
/**
* @param {?} prenomData
* @return {?}
*/
DirectiveNormalizer.prototype.normalizeTemplateSync = function (prenomData) {
return this.normalizeLoadedTemplate(prenomData, /** @type {?} */ ((prenomData.template)), prenomData.moduleUrl);
};
/**
* @param {?} prenomData
* @return {?}
*/
DirectiveNormalizer.prototype.normalizeTemplateAsync = function (prenomData) {
var _this = this;
var /** @type {?} */ templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, /** @type {?} */ ((prenomData.templateUrl)));
return this._fetch(templateUrl)
.then(function (value) { return _this.normalizeLoadedTemplate(prenomData, value, templateUrl); });
};
/**
* @param {?} prenormData
* @param {?} template
* @param {?} templateAbsUrl
* @return {?}
*/
DirectiveNormalizer.prototype.normalizeLoadedTemplate = function (prenormData, template, templateAbsUrl) {
var /** @type {?} */ isInline = !!prenormData.template;
var /** @type {?} */ interpolationConfig = InterpolationConfig.fromArray(/** @type {?} */ ((prenormData.interpolation)));
var /** @type {?} */ rootNodesAndErrors = this._htmlParser.parse(template, templateSourceUrl({ reference: prenormData.ngModuleType }, { type: { reference: prenormData.componentType } }, { isInline: isInline, templateUrl: templateAbsUrl }), true, interpolationConfig);
if (rootNodesAndErrors.errors.length > 0) {
var /** @type {?} */ errorString = rootNodesAndErrors.errors.join('\n');
throw syntaxError("Template parse errors:\n" + errorString);
}
var /** @type {?} */ templateMetadataStyles = this.normalizeStylesheet(new CompileStylesheetMetadata({
styles: prenormData.styles,
styleUrls: prenormData.styleUrls,
moduleUrl: prenormData.moduleUrl
}));
var /** @type {?} */ visitor = new TemplatePreparseVisitor();
visitAll(visitor, rootNodesAndErrors.rootNodes);
var /** @type {?} */ templateStyles = this.normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl }));
var /** @type {?} */ encapsulation = prenormData.encapsulation;
if (encapsulation == null) {
encapsulation = this._config.defaultEncapsulation;
}
var /** @type {?} */ styles = templateMetadataStyles.styles.concat(templateStyles.styles);
var /** @type {?} */ styleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
if (encapsulation === __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].Emulated && styles.length === 0 &&
styleUrls.length === 0) {
encapsulation = __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].None;
}
return new CompileTemplateMetadata({
encapsulation: encapsulation,
template: template,
templateUrl: templateAbsUrl, styles: styles, styleUrls: styleUrls,
ngContentSelectors: visitor.ngContentSelectors,
animations: prenormData.animations,
interpolation: prenormData.interpolation, isInline: isInline,
externalStylesheets: []
});
};
/**
* @param {?} templateMeta
* @return {?}
*/
DirectiveNormalizer.prototype.normalizeExternalStylesheets = function (templateMeta) {
return this._loadMissingExternalStylesheets(templateMeta.styleUrls)
.then(function (externalStylesheets) { return new CompileTemplateMetadata({
encapsulation: templateMeta.encapsulation,
template: templateMeta.template,
templateUrl: templateMeta.templateUrl,
styles: templateMeta.styles,
styleUrls: templateMeta.styleUrls,
externalStylesheets: externalStylesheets,
ngContentSelectors: templateMeta.ngContentSelectors,
animations: templateMeta.animations,
interpolation: templateMeta.interpolation,
isInline: templateMeta.isInline,
}); });
};
/**
* @param {?} styleUrls
* @param {?=} loadedStylesheets
* @return {?}
*/
DirectiveNormalizer.prototype._loadMissingExternalStylesheets = function (styleUrls, loadedStylesheets) {
var _this = this;
if (loadedStylesheets === void 0) { loadedStylesheets = new Map(); }
return Promise
.all(styleUrls.filter(function (styleUrl) { return !loadedStylesheets.has(styleUrl); })
.map(function (styleUrl) { return _this._fetch(styleUrl).then(function (loadedStyle) {
var /** @type {?} */ stylesheet = _this.normalizeStylesheet(new CompileStylesheetMetadata({ styles: [loadedStyle], moduleUrl: styleUrl }));
loadedStylesheets.set(styleUrl, stylesheet);
return _this._loadMissingExternalStylesheets(stylesheet.styleUrls, loadedStylesheets);
}); }))
.then(function (_) { return Array.from(loadedStylesheets.values()); });
};
/**
* @param {?} stylesheet
* @return {?}
*/
DirectiveNormalizer.prototype.normalizeStylesheet = function (stylesheet) {
var _this = this;
var /** @type {?} */ moduleUrl = ((stylesheet.moduleUrl));
var /** @type {?} */ allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
.map(function (url) { return _this._urlResolver.resolve(moduleUrl, url); });
var /** @type {?} */ allStyles = stylesheet.styles.map(function (style$$1) {
var /** @type {?} */ styleWithImports = extractStyleUrls(_this._urlResolver, moduleUrl, style$$1);
allStyleUrls.push.apply(allStyleUrls, styleWithImports.styleUrls);
return styleWithImports.style;
});
return new CompileStylesheetMetadata({ styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl });
};
return DirectiveNormalizer;
}());
DirectiveNormalizer.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
DirectiveNormalizer.ctorParameters = function () { return [
{ type: ResourceLoader, },
{ type: UrlResolver, },
{ type: HtmlParser, },
{ type: CompilerConfig, },
]; };
var TemplatePreparseVisitor = (function () {
function TemplatePreparseVisitor() {
this.ngContentSelectors = [];
this.styles = [];
this.styleUrls = [];
this.ngNonBindableStackCount = 0;
}
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
TemplatePreparseVisitor.prototype.visitElement = function (ast, context) {
var /** @type {?} */ preparsedElement = preparseElement(ast);
switch (preparsedElement.type) {
case PreparsedElementType.NG_CONTENT:
if (this.ngNonBindableStackCount === 0) {
this.ngContentSelectors.push(preparsedElement.selectAttr);
}
break;
case PreparsedElementType.STYLE:
var /** @type {?} */ textContent_1 = '';
ast.children.forEach(function (child) {
if (child instanceof Text) {
textContent_1 += child.value;
}
});
this.styles.push(textContent_1);
break;
case PreparsedElementType.STYLESHEET:
this.styleUrls.push(preparsedElement.hrefAttr);
break;
default:
break;
}
if (preparsedElement.nonBindable) {
this.ngNonBindableStackCount++;
}
visitAll(this, ast.children);
if (preparsedElement.nonBindable) {
this.ngNonBindableStackCount--;
}
return null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
TemplatePreparseVisitor.prototype.visitExpansion = function (ast, context) { visitAll(this, ast.cases); };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
TemplatePreparseVisitor.prototype.visitExpansionCase = function (ast, context) {
visitAll(this, ast.expression);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
TemplatePreparseVisitor.prototype.visitComment = function (ast, context) { return null; };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
TemplatePreparseVisitor.prototype.visitAttribute = function (ast, context) { return null; };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
TemplatePreparseVisitor.prototype.visitText = function (ast, context) { return null; };
return TemplatePreparseVisitor;
}());
/**
* @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
*/
var __assign = (undefined && undefined.__assign) || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var DirectiveResolver = (function () {
/**
* @param {?=} _reflector
*/
function DirectiveResolver(_reflector) {
if (_reflector === void 0) { _reflector = __WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */]; }
this._reflector = _reflector;
}
/**
* @param {?} type
* @return {?}
*/
DirectiveResolver.prototype.isDirective = function (type) {
var /** @type {?} */ typeMetadata = this._reflector.annotations(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(type));
return typeMetadata && typeMetadata.some(isDirectiveMetadata);
};
/**
* @param {?} type
* @param {?=} throwIfNotFound
* @return {?}
*/
DirectiveResolver.prototype.resolve = function (type, throwIfNotFound) {
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var /** @type {?} */ typeMetadata = this._reflector.annotations(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(type));
if (typeMetadata) {
var /** @type {?} */ metadata = findLast(typeMetadata, isDirectiveMetadata);
if (metadata) {
var /** @type {?} */ propertyMetadata = this._reflector.propMetadata(type);
return this._mergeWithPropertyMetadata(metadata, propertyMetadata, type);
}
}
if (throwIfNotFound) {
throw new Error("No Directive annotation found on " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(type));
}
return null;
};
/**
* @param {?} dm
* @param {?} propertyMetadata
* @param {?} directiveType
* @return {?}
*/
DirectiveResolver.prototype._mergeWithPropertyMetadata = function (dm, propertyMetadata, directiveType) {
var /** @type {?} */ inputs = [];
var /** @type {?} */ outputs = [];
var /** @type {?} */ host = {};
var /** @type {?} */ queries = {};
Object.keys(propertyMetadata).forEach(function (propName) {
var /** @type {?} */ input = findLast(propertyMetadata[propName], function (a) { return a instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */]; });
if (input) {
if (input.bindingPropertyName) {
inputs.push(propName + ": " + input.bindingPropertyName);
}
else {
inputs.push(propName);
}
}
var /** @type {?} */ output = findLast(propertyMetadata[propName], function (a) { return a instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["t" /* Output */]; });
if (output) {
if (output.bindingPropertyName) {
outputs.push(propName + ": " + output.bindingPropertyName);
}
else {
outputs.push(propName);
}
}
var /** @type {?} */ hostBindings = propertyMetadata[propName].filter(function (a) { return a && a instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["_7" /* HostBinding */]; });
hostBindings.forEach(function (hostBinding) {
if (hostBinding.hostPropertyName) {
var /** @type {?} */ startWith = hostBinding.hostPropertyName[0];
if (startWith === '(') {
throw new Error("@HostBinding can not bind to events. Use @HostListener instead.");
}
else if (startWith === '[') {
throw new Error("@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.");
}
host["[" + hostBinding.hostPropertyName + "]"] = propName;
}
else {
host["[" + propName + "]"] = propName;
}
});
var /** @type {?} */ hostListeners = propertyMetadata[propName].filter(function (a) { return a && a instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["_6" /* HostListener */]; });
hostListeners.forEach(function (hostListener) {
var /** @type {?} */ args = hostListener.args || [];
host["(" + hostListener.eventName + ")"] = propName + "(" + args.join(',') + ")";
});
var /** @type {?} */ query = findLast(propertyMetadata[propName], function (a) { return a instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["_50" /* Query */]; });
if (query) {
queries[propName] = query;
}
});
return this._merge(dm, inputs, outputs, host, queries, directiveType);
};
/**
* @param {?} def
* @return {?}
*/
DirectiveResolver.prototype._extractPublicName = function (def) { return splitAtColon(def, [/** @type {?} */ ((null)), def])[1].trim(); };
/**
* @param {?} bindings
* @return {?}
*/
DirectiveResolver.prototype._dedupeBindings = function (bindings) {
var /** @type {?} */ names = new Set();
var /** @type {?} */ reversedResult = [];
// go last to first to allow later entries to overwrite previous entries
for (var /** @type {?} */ i = bindings.length - 1; i >= 0; i--) {
var /** @type {?} */ binding = bindings[i];
var /** @type {?} */ name = this._extractPublicName(binding);
if (!names.has(name)) {
names.add(name);
reversedResult.push(binding);
}
}
return reversedResult.reverse();
};
/**
* @param {?} directive
* @param {?} inputs
* @param {?} outputs
* @param {?} host
* @param {?} queries
* @param {?} directiveType
* @return {?}
*/
DirectiveResolver.prototype._merge = function (directive, inputs, outputs, host, queries, directiveType) {
var /** @type {?} */ mergedInputs = this._dedupeBindings(directive.inputs ? directive.inputs.concat(inputs) : inputs);
var /** @type {?} */ mergedOutputs = this._dedupeBindings(directive.outputs ? directive.outputs.concat(outputs) : outputs);
var /** @type {?} */ mergedHost = directive.host ? __assign({}, directive.host, host) : host;
var /** @type {?} */ mergedQueries = directive.queries ? __assign({}, directive.queries, queries) : queries;
if (directive instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["_3" /* Component */]) {
return new __WEBPACK_IMPORTED_MODULE_0__angular_core__["_3" /* Component */]({
selector: directive.selector,
inputs: mergedInputs,
outputs: mergedOutputs,
host: mergedHost,
exportAs: directive.exportAs,
moduleId: directive.moduleId,
queries: mergedQueries,
changeDetection: directive.changeDetection,
providers: directive.providers,
viewProviders: directive.viewProviders,
entryComponents: directive.entryComponents,
template: directive.template,
templateUrl: directive.templateUrl,
styles: directive.styles,
styleUrls: directive.styleUrls,
encapsulation: directive.encapsulation,
animations: directive.animations,
interpolation: directive.interpolation
});
}
else {
return new __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */]({
selector: directive.selector,
inputs: mergedInputs,
outputs: mergedOutputs,
host: mergedHost,
exportAs: directive.exportAs,
queries: mergedQueries,
providers: directive.providers
});
}
};
return DirectiveResolver;
}());
DirectiveResolver.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
DirectiveResolver.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_51" /* ɵReflectorReader */], },
]; };
/**
* @param {?} type
* @return {?}
*/
function isDirectiveMetadata(type) {
return type instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */];
}
/**
* @template T
* @param {?} arr
* @param {?} condition
* @return {?}
*/
function findLast(arr, condition) {
for (var /** @type {?} */ i = arr.length - 1; i >= 0; i--) {
if (condition(arr[i])) {
return arr[i];
}
}
return null;
}
/**
* @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
*/
var STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
var NG_FACTORY = /\.ngfactory\./;
/**
* @param {?} filePath
* @return {?}
*/
function ngfactoryFilePath(filePath) {
var /** @type {?} */ urlWithSuffix = splitTypescriptSuffix(filePath);
return urlWithSuffix[0] + ".ngfactory" + urlWithSuffix[1];
}
/**
* @param {?} filePath
* @return {?}
*/
function stripNgFactory(filePath) {
return filePath.replace(NG_FACTORY, '.');
}
/**
* @param {?} filePath
* @return {?}
*/
function isNgFactoryFile(filePath) {
return NG_FACTORY.test(filePath);
}
/**
* @param {?} path
* @return {?}
*/
function splitTypescriptSuffix(path) {
if (path.endsWith('.d.ts')) {
return [path.slice(0, -5), '.ts'];
}
var /** @type {?} */ lastDot = path.lastIndexOf('.');
if (lastDot !== -1) {
return [path.substring(0, lastDot), path.substring(lastDot)];
}
return [path, ''];
}
/**
* @param {?} fileName
* @return {?}
*/
function summaryFileName(fileName) {
var /** @type {?} */ fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
return fileNameWithoutSuffix + ".ngsummary.json";
}
/**
* @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
*/
/**
* @param {?} hook
* @param {?} token
* @return {?}
*/
function hasLifecycleHook(hook, token) {
return __WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */].hasLifecycleHook(token, getHookName(hook));
}
/**
* @param {?} hook
* @return {?}
*/
function getHookName(hook) {
switch (hook) {
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnInit:
return 'ngOnInit';
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnDestroy:
return 'ngOnDestroy';
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].DoCheck:
return 'ngDoCheck';
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnChanges:
return 'ngOnChanges';
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].AfterContentInit:
return 'ngAfterContentInit';
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].AfterContentChecked:
return 'ngAfterContentChecked';
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].AfterViewInit:
return 'ngAfterViewInit';
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].AfterViewChecked:
return 'ngAfterViewChecked';
}
}
/**
* @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
*/
/**
* @param {?} obj
* @return {?}
*/
function _isNgModuleMetadata(obj) {
return obj instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */];
}
/**
* Resolves types to {\@link NgModule}.
*/
var NgModuleResolver = (function () {
/**
* @param {?=} _reflector
*/
function NgModuleResolver(_reflector) {
if (_reflector === void 0) { _reflector = __WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */]; }
this._reflector = _reflector;
}
/**
* @param {?} type
* @return {?}
*/
NgModuleResolver.prototype.isNgModule = function (type) { return this._reflector.annotations(type).some(_isNgModuleMetadata); };
/**
* @param {?} type
* @param {?=} throwIfNotFound
* @return {?}
*/
NgModuleResolver.prototype.resolve = function (type, throwIfNotFound) {
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var /** @type {?} */ ngModuleMeta = findLast(this._reflector.annotations(type), _isNgModuleMetadata);
if (ngModuleMeta) {
return ngModuleMeta;
}
else {
if (throwIfNotFound) {
throw new Error("No NgModule metadata found for '" + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(type) + "'.");
}
return null;
}
};
return NgModuleResolver;
}());
NgModuleResolver.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
NgModuleResolver.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_51" /* ɵReflectorReader */], },
]; };
/**
* @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
*/
/**
* @param {?} type
* @return {?}
*/
function _isPipeMetadata(type) {
return type instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */];
}
/**
* Resolve a `Type` for {\@link Pipe}.
*
* This interface can be overridden by the application developer to create custom behavior.
*
* See {\@link Compiler}
*/
var PipeResolver = (function () {
/**
* @param {?=} _reflector
*/
function PipeResolver(_reflector) {
if (_reflector === void 0) { _reflector = __WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */]; }
this._reflector = _reflector;
}
/**
* @param {?} type
* @return {?}
*/
PipeResolver.prototype.isPipe = function (type) {
var /** @type {?} */ typeMetadata = this._reflector.annotations(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(type));
return typeMetadata && typeMetadata.some(_isPipeMetadata);
};
/**
* Return {\@link Pipe} for a given `Type`.
* @param {?} type
* @param {?=} throwIfNotFound
* @return {?}
*/
PipeResolver.prototype.resolve = function (type, throwIfNotFound) {
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var /** @type {?} */ metas = this._reflector.annotations(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(type));
if (metas) {
var /** @type {?} */ annotation = findLast(metas, _isPipeMetadata);
if (annotation) {
return annotation;
}
}
if (throwIfNotFound) {
throw new Error("No Pipe decorator found on " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(type));
}
return null;
};
return PipeResolver;
}());
PipeResolver.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
PipeResolver.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_51" /* ɵReflectorReader */], },
]; };
/**
* @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
*/
var SummaryResolver = (function () {
function SummaryResolver() {
}
/**
* @param {?} fileName
* @return {?}
*/
SummaryResolver.prototype.isLibraryFile = function (fileName) { return false; };
;
/**
* @param {?} fileName
* @return {?}
*/
SummaryResolver.prototype.getLibraryFileName = function (fileName) { return null; };
/**
* @param {?} reference
* @return {?}
*/
SummaryResolver.prototype.resolveSummary = function (reference) { return null; };
;
/**
* @param {?} filePath
* @return {?}
*/
SummaryResolver.prototype.getSymbolsOf = function (filePath) { return []; };
/**
* @param {?} reference
* @return {?}
*/
SummaryResolver.prototype.getImportAs = function (reference) { return reference; };
return SummaryResolver;
}());
SummaryResolver.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
SummaryResolver.ctorParameters = function () { return []; };
/**
* @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
*/
var ERROR_COLLECTOR_TOKEN = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('ErrorCollector');
var CompileMetadataResolver = (function () {
/**
* @param {?} _config
* @param {?} _ngModuleResolver
* @param {?} _directiveResolver
* @param {?} _pipeResolver
* @param {?} _summaryResolver
* @param {?} _schemaRegistry
* @param {?} _directiveNormalizer
* @param {?} _console
* @param {?} _staticSymbolCache
* @param {?=} _reflector
* @param {?=} _errorCollector
*/
function CompileMetadataResolver(_config, _ngModuleResolver, _directiveResolver, _pipeResolver, _summaryResolver, _schemaRegistry, _directiveNormalizer, _console, _staticSymbolCache, _reflector, _errorCollector) {
if (_reflector === void 0) { _reflector = __WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */]; }
this._config = _config;
this._ngModuleResolver = _ngModuleResolver;
this._directiveResolver = _directiveResolver;
this._pipeResolver = _pipeResolver;
this._summaryResolver = _summaryResolver;
this._schemaRegistry = _schemaRegistry;
this._directiveNormalizer = _directiveNormalizer;
this._console = _console;
this._staticSymbolCache = _staticSymbolCache;
this._reflector = _reflector;
this._errorCollector = _errorCollector;
this._nonNormalizedDirectiveCache = new Map();
this._directiveCache = new Map();
this._summaryCache = new Map();
this._pipeCache = new Map();
this._ngModuleCache = new Map();
this._ngModuleOfTypes = new Map();
}
/**
* @param {?} type
* @return {?}
*/
CompileMetadataResolver.prototype.clearCacheFor = function (type) {
var /** @type {?} */ dirMeta = this._directiveCache.get(type);
this._directiveCache.delete(type);
this._nonNormalizedDirectiveCache.delete(type);
this._summaryCache.delete(type);
this._pipeCache.delete(type);
this._ngModuleOfTypes.delete(type);
// Clear all of the NgModule as they contain transitive information!
this._ngModuleCache.clear();
if (dirMeta) {
this._directiveNormalizer.clearCacheFor(dirMeta);
}
};
/**
* @return {?}
*/
CompileMetadataResolver.prototype.clearCache = function () {
this._directiveCache.clear();
this._nonNormalizedDirectiveCache.clear();
this._summaryCache.clear();
this._pipeCache.clear();
this._ngModuleCache.clear();
this._ngModuleOfTypes.clear();
this._directiveNormalizer.clearCache();
};
/**
* @param {?} baseType
* @param {?} name
* @return {?}
*/
CompileMetadataResolver.prototype._createProxyClass = function (baseType, name) {
var /** @type {?} */ delegate = null;
var /** @type {?} */ proxyClass = (function () {
if (!delegate) {
throw new Error("Illegal state: Class " + name + " for type " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(baseType) + " is not compiled yet!");
}
return delegate.apply(this, arguments);
});
proxyClass.setDelegate = function (d) {
delegate = d;
((proxyClass)).prototype = d.prototype;
};
// Make stringify work correctly
((proxyClass)).overriddenName = name;
return proxyClass;
};
/**
* @param {?} dirType
* @param {?} name
* @return {?}
*/
CompileMetadataResolver.prototype.getGeneratedClass = function (dirType, name) {
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
}
else {
return this._createProxyClass(dirType, name);
}
};
/**
* @param {?} dirType
* @return {?}
*/
CompileMetadataResolver.prototype.getComponentViewClass = function (dirType) {
return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
};
/**
* @param {?} dirType
* @return {?}
*/
CompileMetadataResolver.prototype.getHostComponentViewClass = function (dirType) {
return this.getGeneratedClass(dirType, hostViewClassName(dirType));
};
/**
* @param {?} dirType
* @return {?}
*/
CompileMetadataResolver.prototype.getHostComponentType = function (dirType) {
var /** @type {?} */ name = identifierName({ reference: dirType }) + "_Host";
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(dirType.filePath, name);
}
else {
var /** @type {?} */ HostClass = (function HostClass() { });
HostClass.overriddenName = name;
return HostClass;
}
};
/**
* @param {?} dirType
* @return {?}
*/
CompileMetadataResolver.prototype.getRendererType = function (dirType) {
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), rendererTypeName(dirType));
}
else {
// returning an object as proxy,
// that we fill later during runtime compilation.
return ({});
}
};
/**
* @param {?} selector
* @param {?} dirType
* @param {?} inputs
* @param {?} outputs
* @return {?}
*/
CompileMetadataResolver.prototype.getComponentFactory = function (selector, dirType, inputs, outputs) {
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
}
else {
var /** @type {?} */ hostView = this.getHostComponentViewClass(dirType);
// Note: ngContentSelectors will be filled later once the template is
// loaded.
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_46" /* ɵccf */])(selector, dirType, /** @type {?} */ (hostView), inputs, outputs, []);
}
};
/**
* @param {?} factory
* @param {?} ngContentSelectors
* @return {?}
*/
CompileMetadataResolver.prototype.initComponentFactory = function (factory, ngContentSelectors) {
if (!(factory instanceof StaticSymbol)) {
(_a = factory.ngContentSelectors).push.apply(_a, ngContentSelectors);
}
var _a;
};
/**
* @param {?} type
* @param {?} kind
* @return {?}
*/
CompileMetadataResolver.prototype._loadSummary = function (type, kind) {
var /** @type {?} */ typeSummary = this._summaryCache.get(type);
if (!typeSummary) {
var /** @type {?} */ summary = this._summaryResolver.resolveSummary(type);
typeSummary = summary ? summary.type : null;
this._summaryCache.set(type, typeSummary || null);
}
return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
};
/**
* @param {?} ngModuleType
* @param {?} directiveType
* @param {?} isSync
* @return {?}
*/
CompileMetadataResolver.prototype._loadDirectiveMetadata = function (ngModuleType, directiveType, isSync) {
var _this = this;
if (this._directiveCache.has(directiveType)) {
return null;
}
directiveType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(directiveType);
var _a = ((this.getNonNormalizedDirectiveMetadata(directiveType))), annotation = _a.annotation, metadata = _a.metadata;
var /** @type {?} */ createDirectiveMetadata = function (templateMetadata) {
var /** @type {?} */ normalizedDirMeta = new CompileDirectiveMetadata({
isHost: false,
type: metadata.type,
isComponent: metadata.isComponent,
selector: metadata.selector,
exportAs: metadata.exportAs,
changeDetection: metadata.changeDetection,
inputs: metadata.inputs,
outputs: metadata.outputs,
hostListeners: metadata.hostListeners,
hostProperties: metadata.hostProperties,
hostAttributes: metadata.hostAttributes,
providers: metadata.providers,
viewProviders: metadata.viewProviders,
queries: metadata.queries,
viewQueries: metadata.viewQueries,
entryComponents: metadata.entryComponents,
componentViewType: metadata.componentViewType,
rendererType: metadata.rendererType,
componentFactory: metadata.componentFactory,
template: templateMetadata
});
if (templateMetadata) {
_this.initComponentFactory(/** @type {?} */ ((metadata.componentFactory)), templateMetadata.ngContentSelectors);
}
_this._directiveCache.set(directiveType, normalizedDirMeta);
_this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
return normalizedDirMeta;
};
if (metadata.isComponent) {
var /** @type {?} */ template = ((metadata.template));
var /** @type {?} */ templateMeta = this._directiveNormalizer.normalizeTemplate({
ngModuleType: ngModuleType,
componentType: directiveType,
moduleUrl: componentModuleUrl(this._reflector, directiveType, annotation),
encapsulation: template.encapsulation,
template: template.template,
templateUrl: template.templateUrl,
styles: template.styles,
styleUrls: template.styleUrls,
animations: template.animations,
interpolation: template.interpolation
});
if (templateMeta.syncResult) {
createDirectiveMetadata(templateMeta.syncResult);
return null;
}
else {
if (isSync) {
this._reportError(componentStillLoadingError(directiveType), directiveType);
return null;
}
return ((templateMeta.asyncResult)).then(createDirectiveMetadata);
}
}
else {
// directive
createDirectiveMetadata(null);
return null;
}
};
/**
* @param {?} directiveType
* @return {?}
*/
CompileMetadataResolver.prototype.getNonNormalizedDirectiveMetadata = function (directiveType) {
var _this = this;
directiveType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(directiveType);
if (!directiveType) {
return null;
}
var /** @type {?} */ cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
if (cacheEntry) {
return cacheEntry;
}
var /** @type {?} */ dirMeta = this._directiveResolver.resolve(directiveType, false);
if (!dirMeta) {
return null;
}
var /** @type {?} */ nonNormalizedTemplateMetadata = ((undefined));
if (dirMeta instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["_3" /* Component */]) {
// component
assertArrayOfStrings('styles', dirMeta.styles);
assertArrayOfStrings('styleUrls', dirMeta.styleUrls);
assertInterpolationSymbols('interpolation', dirMeta.interpolation);
var /** @type {?} */ animations = dirMeta.animations;
nonNormalizedTemplateMetadata = new CompileTemplateMetadata({
encapsulation: noUndefined(dirMeta.encapsulation),
template: noUndefined(dirMeta.template),
templateUrl: noUndefined(dirMeta.templateUrl),
styles: dirMeta.styles || [],
styleUrls: dirMeta.styleUrls || [],
animations: animations || [],
interpolation: noUndefined(dirMeta.interpolation),
isInline: !!dirMeta.template,
externalStylesheets: [],
ngContentSelectors: []
});
}
var /** @type {?} */ changeDetectionStrategy = ((null));
var /** @type {?} */ viewProviders = [];
var /** @type {?} */ entryComponentMetadata = [];
var /** @type {?} */ selector = dirMeta.selector;
if (dirMeta instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["_3" /* Component */]) {
// Component
changeDetectionStrategy = ((dirMeta.changeDetection));
if (dirMeta.viewProviders) {
viewProviders = this._getProvidersMetadata(dirMeta.viewProviders, entryComponentMetadata, "viewProviders for \"" + stringifyType(directiveType) + "\"", [], directiveType);
}
if (dirMeta.entryComponents) {
entryComponentMetadata = flattenAndDedupeArray(dirMeta.entryComponents)
.map(function (type) { return ((_this._getEntryComponentMetadata(type))); })
.concat(entryComponentMetadata);
}
if (!selector) {
selector = this._schemaRegistry.getDefaultComponentElementName();
}
}
else {
// Directive
if (!selector) {
this._reportError(syntaxError("Directive " + stringifyType(directiveType) + " has no selector, please add it!"), directiveType);
selector = 'error';
}
}
var /** @type {?} */ providers = [];
if (dirMeta.providers != null) {
providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, "providers for \"" + stringifyType(directiveType) + "\"", [], directiveType);
}
var /** @type {?} */ queries = [];
var /** @type {?} */ viewQueries = [];
if (dirMeta.queries != null) {
queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
}
var /** @type {?} */ metadata = CompileDirectiveMetadata.create({
isHost: false,
selector: selector,
exportAs: noUndefined(dirMeta.exportAs),
isComponent: !!nonNormalizedTemplateMetadata,
type: this._getTypeMetadata(directiveType),
template: nonNormalizedTemplateMetadata,
changeDetection: changeDetectionStrategy,
inputs: dirMeta.inputs || [],
outputs: dirMeta.outputs || [],
host: dirMeta.host || {},
providers: providers || [],
viewProviders: viewProviders || [],
queries: queries || [],
viewQueries: viewQueries || [],
entryComponents: entryComponentMetadata,
componentViewType: nonNormalizedTemplateMetadata ? this.getComponentViewClass(directiveType) :
null,
rendererType: nonNormalizedTemplateMetadata ? this.getRendererType(directiveType) : null,
componentFactory: null
});
if (nonNormalizedTemplateMetadata) {
metadata.componentFactory =
this.getComponentFactory(selector, directiveType, metadata.inputs, metadata.outputs);
}
cacheEntry = { metadata: metadata, annotation: dirMeta };
this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
return cacheEntry;
};
/**
* Gets the metadata for the given directive.
* This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
* @param {?} directiveType
* @return {?}
*/
CompileMetadataResolver.prototype.getDirectiveMetadata = function (directiveType) {
var /** @type {?} */ dirMeta = ((this._directiveCache.get(directiveType)));
if (!dirMeta) {
this._reportError(syntaxError("Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive " + stringifyType(directiveType) + "."), directiveType);
}
return dirMeta;
};
/**
* @param {?} dirType
* @return {?}
*/
CompileMetadataResolver.prototype.getDirectiveSummary = function (dirType) {
var /** @type {?} */ dirSummary = (this._loadSummary(dirType, CompileSummaryKind.Directive));
if (!dirSummary) {
this._reportError(syntaxError("Illegal state: Could not load the summary for directive " + stringifyType(dirType) + "."), dirType);
}
return dirSummary;
};
/**
* @param {?} type
* @return {?}
*/
CompileMetadataResolver.prototype.isDirective = function (type) { return this._directiveResolver.isDirective(type); };
/**
* @param {?} type
* @return {?}
*/
CompileMetadataResolver.prototype.isPipe = function (type) { return this._pipeResolver.isPipe(type); };
/**
* @param {?} moduleType
* @return {?}
*/
CompileMetadataResolver.prototype.getNgModuleSummary = function (moduleType) {
var /** @type {?} */ moduleSummary = (this._loadSummary(moduleType, CompileSummaryKind.NgModule));
if (!moduleSummary) {
var /** @type {?} */ moduleMeta = this.getNgModuleMetadata(moduleType, false);
moduleSummary = moduleMeta ? moduleMeta.toSummary() : null;
if (moduleSummary) {
this._summaryCache.set(moduleType, moduleSummary);
}
}
return moduleSummary;
};
/**
* Loads the declared directives and pipes of an NgModule.
* @param {?} moduleType
* @param {?} isSync
* @param {?=} throwIfNotFound
* @return {?}
*/
CompileMetadataResolver.prototype.loadNgModuleDirectiveAndPipeMetadata = function (moduleType, isSync, throwIfNotFound) {
var _this = this;
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var /** @type {?} */ ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
var /** @type {?} */ loading = [];
if (ngModule) {
ngModule.declaredDirectives.forEach(function (id) {
var /** @type {?} */ promise = _this._loadDirectiveMetadata(moduleType, id.reference, isSync);
if (promise) {
loading.push(promise);
}
});
ngModule.declaredPipes.forEach(function (id) { return _this._loadPipeMetadata(id.reference); });
}
return Promise.all(loading);
};
/**
* @param {?} moduleType
* @param {?=} throwIfNotFound
* @return {?}
*/
CompileMetadataResolver.prototype.getNgModuleMetadata = function (moduleType, throwIfNotFound) {
var _this = this;
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
moduleType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(moduleType);
var /** @type {?} */ compileMeta = this._ngModuleCache.get(moduleType);
if (compileMeta) {
return compileMeta;
}
var /** @type {?} */ meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
if (!meta) {
return null;
}
var /** @type {?} */ declaredDirectives = [];
var /** @type {?} */ exportedNonModuleIdentifiers = [];
var /** @type {?} */ declaredPipes = [];
var /** @type {?} */ importedModules = [];
var /** @type {?} */ exportedModules = [];
var /** @type {?} */ providers = [];
var /** @type {?} */ entryComponents = [];
var /** @type {?} */ bootstrapComponents = [];
var /** @type {?} */ schemas = [];
if (meta.imports) {
flattenAndDedupeArray(meta.imports).forEach(function (importedType) {
var /** @type {?} */ importedModuleType = ((undefined));
if (isValidType(importedType)) {
importedModuleType = importedType;
}
else if (importedType && importedType.ngModule) {
var /** @type {?} */ moduleWithProviders = importedType;
importedModuleType = moduleWithProviders.ngModule;
if (moduleWithProviders.providers) {
providers.push.apply(providers, _this._getProvidersMetadata(moduleWithProviders.providers, entryComponents, "provider for the NgModule '" + stringifyType(importedModuleType) + "'", [], importedType));
}
}
if (importedModuleType) {
if (_this._checkSelfImport(moduleType, importedModuleType))
return;
var /** @type {?} */ importedModuleSummary = _this.getNgModuleSummary(importedModuleType);
if (!importedModuleSummary) {
_this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(importedType) + " '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'. Please add a @NgModule annotation."), moduleType);
return;
}
importedModules.push(importedModuleSummary);
}
else {
_this._reportError(syntaxError("Unexpected value '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
});
}
if (meta.exports) {
flattenAndDedupeArray(meta.exports).forEach(function (exportedType) {
if (!isValidType(exportedType)) {
_this._reportError(syntaxError("Unexpected value '" + stringifyType(exportedType) + "' exported by the module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
var /** @type {?} */ exportedModuleSummary = _this.getNgModuleSummary(exportedType);
if (exportedModuleSummary) {
exportedModules.push(exportedModuleSummary);
}
else {
exportedNonModuleIdentifiers.push(_this._getIdentifierMetadata(exportedType));
}
});
}
// Note: This will be modified later, so we rely on
// getting a new instance every time!
var /** @type {?} */ transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
if (meta.declarations) {
flattenAndDedupeArray(meta.declarations).forEach(function (declaredType) {
if (!isValidType(declaredType)) {
_this._reportError(syntaxError("Unexpected value '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
var /** @type {?} */ declaredIdentifier = _this._getIdentifierMetadata(declaredType);
if (_this._directiveResolver.isDirective(declaredType)) {
transitiveModule.addDirective(declaredIdentifier);
declaredDirectives.push(declaredIdentifier);
_this._addTypeToModule(declaredType, moduleType);
}
else if (_this._pipeResolver.isPipe(declaredType)) {
transitiveModule.addPipe(declaredIdentifier);
transitiveModule.pipes.push(declaredIdentifier);
declaredPipes.push(declaredIdentifier);
_this._addTypeToModule(declaredType, moduleType);
}
else {
_this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(declaredType) + " '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'. Please add a @Pipe/@Directive/@Component annotation."), moduleType);
return;
}
});
}
var /** @type {?} */ exportedDirectives = [];
var /** @type {?} */ exportedPipes = [];
exportedNonModuleIdentifiers.forEach(function (exportedId) {
if (transitiveModule.directivesSet.has(exportedId.reference)) {
exportedDirectives.push(exportedId);
transitiveModule.addExportedDirective(exportedId);
}
else if (transitiveModule.pipesSet.has(exportedId.reference)) {
exportedPipes.push(exportedId);
transitiveModule.addExportedPipe(exportedId);
}
else {
_this._reportError(syntaxError("Can't export " + _this._getTypeDescriptor(exportedId.reference) + " " + stringifyType(exportedId.reference) + " from " + stringifyType(moduleType) + " as it was neither declared nor imported!"), moduleType);
return;
}
});
// The providers of the module have to go last
// so that they overwrite any other provider we already added.
if (meta.providers) {
providers.push.apply(providers, this._getProvidersMetadata(meta.providers, entryComponents, "provider for the NgModule '" + stringifyType(moduleType) + "'", [], moduleType));
}
if (meta.entryComponents) {
entryComponents.push.apply(entryComponents, flattenAndDedupeArray(meta.entryComponents)
.map(function (type) { return ((_this._getEntryComponentMetadata(type))); }));
}
if (meta.bootstrap) {
flattenAndDedupeArray(meta.bootstrap).forEach(function (type) {
if (!isValidType(type)) {
_this._reportError(syntaxError("Unexpected value '" + stringifyType(type) + "' used in the bootstrap property of module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
bootstrapComponents.push(_this._getIdentifierMetadata(type));
});
}
entryComponents.push.apply(entryComponents, bootstrapComponents.map(function (type) { return ((_this._getEntryComponentMetadata(type.reference))); }));
if (meta.schemas) {
schemas.push.apply(schemas, flattenAndDedupeArray(meta.schemas));
}
compileMeta = new CompileNgModuleMetadata({
type: this._getTypeMetadata(moduleType),
providers: providers,
entryComponents: entryComponents,
bootstrapComponents: bootstrapComponents,
schemas: schemas,
declaredDirectives: declaredDirectives,
exportedDirectives: exportedDirectives,
declaredPipes: declaredPipes,
exportedPipes: exportedPipes,
importedModules: importedModules,
exportedModules: exportedModules,
transitiveModule: transitiveModule,
id: meta.id || null,
});
entryComponents.forEach(function (id) { return transitiveModule.addEntryComponent(id); });
providers.forEach(function (provider) { return transitiveModule.addProvider(provider, /** @type {?} */ ((compileMeta)).type); });
transitiveModule.addModule(compileMeta.type);
this._ngModuleCache.set(moduleType, compileMeta);
return compileMeta;
};
/**
* @param {?} moduleType
* @param {?} importedModuleType
* @return {?}
*/
CompileMetadataResolver.prototype._checkSelfImport = function (moduleType, importedModuleType) {
if (moduleType === importedModuleType) {
this._reportError(syntaxError("'" + stringifyType(moduleType) + "' module can't import itself"), moduleType);
return true;
}
return false;
};
/**
* @param {?} type
* @return {?}
*/
CompileMetadataResolver.prototype._getTypeDescriptor = function (type) {
if (this._directiveResolver.isDirective(type)) {
return 'directive';
}
if (this._pipeResolver.isPipe(type)) {
return 'pipe';
}
if (this._ngModuleResolver.isNgModule(type)) {
return 'module';
}
if (((type)).provide) {
return 'provider';
}
return 'value';
};
/**
* @param {?} type
* @param {?} moduleType
* @return {?}
*/
CompileMetadataResolver.prototype._addTypeToModule = function (type, moduleType) {
var /** @type {?} */ oldModule = this._ngModuleOfTypes.get(type);
if (oldModule && oldModule !== moduleType) {
this._reportError(syntaxError("Type " + stringifyType(type) + " is part of the declarations of 2 modules: " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + "! " +
("Please consider moving " + stringifyType(type) + " to a higher module that imports " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ". ") +
("You can also create a new NgModule that exports and includes " + stringifyType(type) + " then import that NgModule in " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ".")), moduleType);
return;
}
this._ngModuleOfTypes.set(type, moduleType);
};
/**
* @param {?} importedModules
* @param {?} exportedModules
* @return {?}
*/
CompileMetadataResolver.prototype._getTransitiveNgModuleMetadata = function (importedModules, exportedModules) {
// collect `providers` / `entryComponents` from all imported and all exported modules
var /** @type {?} */ result = new TransitiveCompileNgModuleMetadata();
var /** @type {?} */ modulesByToken = new Map();
importedModules.concat(exportedModules).forEach(function (modSummary) {
modSummary.modules.forEach(function (mod) { return result.addModule(mod); });
modSummary.entryComponents.forEach(function (comp) { return result.addEntryComponent(comp); });
var /** @type {?} */ addedTokens = new Set();
modSummary.providers.forEach(function (entry) {
var /** @type {?} */ tokenRef = tokenReference(entry.provider.token);
var /** @type {?} */ prevModules = modulesByToken.get(tokenRef);
if (!prevModules) {
prevModules = new Set();
modulesByToken.set(tokenRef, prevModules);
}
var /** @type {?} */ moduleRef = entry.module.reference;
// Note: the providers of one module may still contain multiple providers
// per token (e.g. for multi providers), and we need to preserve these.
if (addedTokens.has(tokenRef) || !prevModules.has(moduleRef)) {
prevModules.add(moduleRef);
addedTokens.add(tokenRef);
result.addProvider(entry.provider, entry.module);
}
});
});
exportedModules.forEach(function (modSummary) {
modSummary.exportedDirectives.forEach(function (id) { return result.addExportedDirective(id); });
modSummary.exportedPipes.forEach(function (id) { return result.addExportedPipe(id); });
});
importedModules.forEach(function (modSummary) {
modSummary.exportedDirectives.forEach(function (id) { return result.addDirective(id); });
modSummary.exportedPipes.forEach(function (id) { return result.addPipe(id); });
});
return result;
};
/**
* @param {?} type
* @return {?}
*/
CompileMetadataResolver.prototype._getIdentifierMetadata = function (type) {
type = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(type);
return { reference: type };
};
/**
* @param {?} type
* @return {?}
*/
CompileMetadataResolver.prototype.isInjectable = function (type) {
var /** @type {?} */ annotations = this._reflector.annotations(type);
// Note: We need an exact check here as @Component / @Directive / ... inherit
// from @CompilerInjectable!
return annotations.some(function (ann) { return ann.constructor === __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */]; });
};
/**
* @param {?} type
* @return {?}
*/
CompileMetadataResolver.prototype.getInjectableSummary = function (type) {
return {
summaryKind: CompileSummaryKind.Injectable,
type: this._getTypeMetadata(type, null, false)
};
};
/**
* @param {?} type
* @param {?=} dependencies
* @return {?}
*/
CompileMetadataResolver.prototype._getInjectableMetadata = function (type, dependencies) {
if (dependencies === void 0) { dependencies = null; }
var /** @type {?} */ typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
if (typeSummary) {
return typeSummary.type;
}
return this._getTypeMetadata(type, dependencies);
};
/**
* @param {?} type
* @param {?=} dependencies
* @param {?=} throwOnUnknownDeps
* @return {?}
*/
CompileMetadataResolver.prototype._getTypeMetadata = function (type, dependencies, throwOnUnknownDeps) {
if (dependencies === void 0) { dependencies = null; }
if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
var /** @type {?} */ identifier = this._getIdentifierMetadata(type);
return {
reference: identifier.reference,
diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
lifecycleHooks: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_53" /* ɵLIFECYCLE_HOOKS_VALUES */].filter(function (hook) { return hasLifecycleHook(hook, identifier.reference); }),
};
};
/**
* @param {?} factory
* @param {?=} dependencies
* @return {?}
*/
CompileMetadataResolver.prototype._getFactoryMetadata = function (factory, dependencies) {
if (dependencies === void 0) { dependencies = null; }
factory = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(factory);
return { reference: factory, diDeps: this._getDependenciesMetadata(factory, dependencies) };
};
/**
* Gets the metadata for the given pipe.
* This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
* @param {?} pipeType
* @return {?}
*/
CompileMetadataResolver.prototype.getPipeMetadata = function (pipeType) {
var /** @type {?} */ pipeMeta = this._pipeCache.get(pipeType);
if (!pipeMeta) {
this._reportError(syntaxError("Illegal state: getPipeMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Pipe " + stringifyType(pipeType) + "."), pipeType);
}
return pipeMeta || null;
};
/**
* @param {?} pipeType
* @return {?}
*/
CompileMetadataResolver.prototype.getPipeSummary = function (pipeType) {
var /** @type {?} */ pipeSummary = (this._loadSummary(pipeType, CompileSummaryKind.Pipe));
if (!pipeSummary) {
this._reportError(syntaxError("Illegal state: Could not load the summary for pipe " + stringifyType(pipeType) + "."), pipeType);
}
return pipeSummary;
};
/**
* @param {?} pipeType
* @return {?}
*/
CompileMetadataResolver.prototype.getOrLoadPipeMetadata = function (pipeType) {
var /** @type {?} */ pipeMeta = this._pipeCache.get(pipeType);
if (!pipeMeta) {
pipeMeta = this._loadPipeMetadata(pipeType);
}
return pipeMeta;
};
/**
* @param {?} pipeType
* @return {?}
*/
CompileMetadataResolver.prototype._loadPipeMetadata = function (pipeType) {
pipeType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(pipeType);
var /** @type {?} */ pipeAnnotation = ((this._pipeResolver.resolve(pipeType)));
var /** @type {?} */ pipeMeta = new CompilePipeMetadata({
type: this._getTypeMetadata(pipeType),
name: pipeAnnotation.name,
pure: !!pipeAnnotation.pure
});
this._pipeCache.set(pipeType, pipeMeta);
this._summaryCache.set(pipeType, pipeMeta.toSummary());
return pipeMeta;
};
/**
* @param {?} typeOrFunc
* @param {?} dependencies
* @param {?=} throwOnUnknownDeps
* @return {?}
*/
CompileMetadataResolver.prototype._getDependenciesMetadata = function (typeOrFunc, dependencies, throwOnUnknownDeps) {
var _this = this;
if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
var /** @type {?} */ hasUnknownDeps = false;
var /** @type {?} */ params = dependencies || this._reflector.parameters(typeOrFunc) || [];
var /** @type {?} */ dependenciesMetadata = params.map(function (param) {
var /** @type {?} */ isAttribute = false;
var /** @type {?} */ isHost = false;
var /** @type {?} */ isSelf = false;
var /** @type {?} */ isSkipSelf = false;
var /** @type {?} */ isOptional = false;
var /** @type {?} */ token = null;
if (Array.isArray(param)) {
param.forEach(function (paramEntry) {
if (paramEntry instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */]) {
isHost = true;
}
else if (paramEntry instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */]) {
isSelf = true;
}
else if (paramEntry instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["s" /* SkipSelf */]) {
isSkipSelf = true;
}
else if (paramEntry instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */]) {
isOptional = true;
}
else if (paramEntry instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["Z" /* Attribute */]) {
isAttribute = true;
token = paramEntry.attributeName;
}
else if (paramEntry instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */]) {
token = paramEntry.token;
}
else if (paramEntry instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]) {
token = paramEntry;
}
else if (isValidType(paramEntry) && token == null) {
token = paramEntry;
}
});
}
else {
token = param;
}
if (token == null) {
hasUnknownDeps = true;
return ((null));
}
return {
isAttribute: isAttribute,
isHost: isHost,
isSelf: isSelf,
isSkipSelf: isSkipSelf,
isOptional: isOptional,
token: _this._getTokenMetadata(token)
};
});
if (hasUnknownDeps) {
var /** @type {?} */ depsTokens = dependenciesMetadata.map(function (dep) { return dep ? stringifyType(dep.token) : '?'; }).join(', ');
var /** @type {?} */ message = "Can't resolve all parameters for " + stringifyType(typeOrFunc) + ": (" + depsTokens + ").";
if (throwOnUnknownDeps) {
this._reportError(syntaxError(message), typeOrFunc);
}
else {
this._console.warn("Warning: " + message + " This will become an error in Angular v5.x");
}
}
return dependenciesMetadata;
};
/**
* @param {?} token
* @return {?}
*/
CompileMetadataResolver.prototype._getTokenMetadata = function (token) {
token = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(token);
var /** @type {?} */ compileToken;
if (typeof token === 'string') {
compileToken = { value: token };
}
else {
compileToken = { identifier: { reference: token } };
}
return compileToken;
};
/**
* @param {?} providers
* @param {?} targetEntryComponents
* @param {?=} debugInfo
* @param {?=} compileProviders
* @param {?=} type
* @return {?}
*/
CompileMetadataResolver.prototype._getProvidersMetadata = function (providers, targetEntryComponents, debugInfo, compileProviders, type) {
var _this = this;
if (compileProviders === void 0) { compileProviders = []; }
providers.forEach(function (provider, providerIdx) {
if (Array.isArray(provider)) {
_this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
}
else {
provider = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(provider);
var /** @type {?} */ providerMeta = ((undefined));
if (provider && typeof provider === 'object' && provider.hasOwnProperty('provide')) {
_this._validateProvider(provider);
providerMeta = new ProviderMeta(provider.provide, provider);
}
else if (isValidType(provider)) {
providerMeta = new ProviderMeta(provider, { useClass: provider });
}
else if (provider === void 0) {
_this._reportError(syntaxError("Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files."));
return;
}
else {
var /** @type {?} */ providersInfo = ((providers.reduce(function (soFar, seenProvider, seenProviderIdx) {
if (seenProviderIdx < providerIdx) {
soFar.push("" + stringifyType(seenProvider));
}
else if (seenProviderIdx == providerIdx) {
soFar.push("?" + stringifyType(seenProvider) + "?");
}
else if (seenProviderIdx == providerIdx + 1) {
soFar.push('...');
}
return soFar;
}, [])))
.join(', ');
_this._reportError(syntaxError("Invalid " + (debugInfo ? debugInfo : 'provider') + " - only instances of Provider and Type are allowed, got: [" + providersInfo + "]"), type);
return;
}
if (providerMeta.token === resolveIdentifier(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) {
targetEntryComponents.push.apply(targetEntryComponents, _this._getEntryComponentsFromProvider(providerMeta, type));
}
else {
compileProviders.push(_this.getProviderMetadata(providerMeta));
}
}
});
return compileProviders;
};
/**
* @param {?} provider
* @return {?}
*/
CompileMetadataResolver.prototype._validateProvider = function (provider) {
if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
this._reportError(syntaxError("Invalid provider for " + stringifyType(provider.provide) + ". useClass cannot be " + provider.useClass + ".\n Usually it happens when:\n 1. There's a circular dependency (might be caused by using index.ts (barrel) files).\n 2. Class was used before it was declared. Use forwardRef in this case."));
}
};
/**
* @param {?} provider
* @param {?=} type
* @return {?}
*/
CompileMetadataResolver.prototype._getEntryComponentsFromProvider = function (provider, type) {
var _this = this;
var /** @type {?} */ components = [];
var /** @type {?} */ collectedIdentifiers = [];
if (provider.useFactory || provider.useExisting || provider.useClass) {
this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!"), type);
return [];
}
if (!provider.multi) {
this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!"), type);
return [];
}
extractIdentifiers(provider.useValue, collectedIdentifiers);
collectedIdentifiers.forEach(function (identifier) {
var /** @type {?} */ entry = _this._getEntryComponentMetadata(identifier.reference, false);
if (entry) {
components.push(entry);
}
});
return components;
};
/**
* @param {?} dirType
* @param {?=} throwIfNotFound
* @return {?}
*/
CompileMetadataResolver.prototype._getEntryComponentMetadata = function (dirType, throwIfNotFound) {
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var /** @type {?} */ dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
if (dirMeta && dirMeta.metadata.isComponent) {
return { componentType: dirType, componentFactory: /** @type {?} */ ((dirMeta.metadata.componentFactory)) };
}
var /** @type {?} */ dirSummary = (this._loadSummary(dirType, CompileSummaryKind.Directive));
if (dirSummary && dirSummary.isComponent) {
return { componentType: dirType, componentFactory: /** @type {?} */ ((dirSummary.componentFactory)) };
}
if (throwIfNotFound) {
throw syntaxError(dirType.name + " cannot be used as an entry component.");
}
return null;
};
/**
* @param {?} provider
* @return {?}
*/
CompileMetadataResolver.prototype.getProviderMetadata = function (provider) {
var /** @type {?} */ compileDeps = ((undefined));
var /** @type {?} */ compileTypeMetadata = ((null));
var /** @type {?} */ compileFactoryMetadata = ((null));
var /** @type {?} */ token = this._getTokenMetadata(provider.token);
if (provider.useClass) {
compileTypeMetadata = this._getInjectableMetadata(provider.useClass, provider.dependencies);
compileDeps = compileTypeMetadata.diDeps;
if (provider.token === provider.useClass) {
// use the compileTypeMetadata as it contains information about lifecycleHooks...
token = { identifier: compileTypeMetadata };
}
}
else if (provider.useFactory) {
compileFactoryMetadata = this._getFactoryMetadata(provider.useFactory, provider.dependencies);
compileDeps = compileFactoryMetadata.diDeps;
}
return {
token: token,
useClass: compileTypeMetadata,
useValue: provider.useValue,
useFactory: compileFactoryMetadata,
useExisting: provider.useExisting ? this._getTokenMetadata(provider.useExisting) : undefined,
deps: compileDeps,
multi: provider.multi
};
};
/**
* @param {?} queries
* @param {?} isViewQuery
* @param {?} directiveType
* @return {?}
*/
CompileMetadataResolver.prototype._getQueriesMetadata = function (queries, isViewQuery, directiveType) {
var _this = this;
var /** @type {?} */ res = [];
Object.keys(queries).forEach(function (propertyName) {
var /** @type {?} */ query = queries[propertyName];
if (query.isViewQuery === isViewQuery) {
res.push(_this._getQueryMetadata(query, propertyName, directiveType));
}
});
return res;
};
/**
* @param {?} selector
* @return {?}
*/
CompileMetadataResolver.prototype._queryVarBindings = function (selector) { return selector.split(/\s*,\s*/); };
/**
* @param {?} q
* @param {?} propertyName
* @param {?} typeOrFunc
* @return {?}
*/
CompileMetadataResolver.prototype._getQueryMetadata = function (q, propertyName, typeOrFunc) {
var _this = this;
var /** @type {?} */ selectors;
if (typeof q.selector === 'string') {
selectors =
this._queryVarBindings(q.selector).map(function (varName) { return _this._getTokenMetadata(varName); });
}
else {
if (!q.selector) {
this._reportError(syntaxError("Can't construct a query for the property \"" + propertyName + "\" of \"" + stringifyType(typeOrFunc) + "\" since the query selector wasn't defined."), typeOrFunc);
selectors = [];
}
else {
selectors = [this._getTokenMetadata(q.selector)];
}
}
return {
selectors: selectors,
first: q.first,
descendants: q.descendants, propertyName: propertyName,
read: q.read ? this._getTokenMetadata(q.read) : ((null))
};
};
/**
* @param {?} error
* @param {?=} type
* @param {?=} otherType
* @return {?}
*/
CompileMetadataResolver.prototype._reportError = function (error, type, otherType) {
if (this._errorCollector) {
this._errorCollector(error, type);
if (otherType) {
this._errorCollector(error, otherType);
}
}
else {
throw error;
}
};
return CompileMetadataResolver;
}());
CompileMetadataResolver.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
CompileMetadataResolver.ctorParameters = function () { return [
{ type: CompilerConfig, },
{ type: NgModuleResolver, },
{ type: DirectiveResolver, },
{ type: PipeResolver, },
{ type: SummaryResolver, },
{ type: ElementSchemaRegistry, },
{ type: DirectiveNormalizer, },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_47" /* ɵConsole */], },
{ type: StaticSymbolCache, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] },] },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_51" /* ɵReflectorReader */], },
{ type: undefined, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */] }, { type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [ERROR_COLLECTOR_TOKEN,] },] },
]; };
/**
* @param {?} tree
* @param {?=} out
* @return {?}
*/
function flattenArray(tree, out) {
if (out === void 0) { out = []; }
if (tree) {
for (var /** @type {?} */ i = 0; i < tree.length; i++) {
var /** @type {?} */ item = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_49" /* resolveForwardRef */])(tree[i]);
if (Array.isArray(item)) {
flattenArray(item, out);
}
else {
out.push(item);
}
}
}
return out;
}
/**
* @param {?} array
* @return {?}
*/
function dedupeArray(array) {
if (array) {
return Array.from(new Set(array));
}
return [];
}
/**
* @param {?} tree
* @return {?}
*/
function flattenAndDedupeArray(tree) {
return dedupeArray(flattenArray(tree));
}
/**
* @param {?} value
* @return {?}
*/
function isValidType(value) {
return (value instanceof StaticSymbol) || (value instanceof __WEBPACK_IMPORTED_MODULE_0__angular_core__["_54" /* Type */]);
}
/**
* @param {?} reflector
* @param {?} type
* @param {?} cmpMetadata
* @return {?}
*/
function componentModuleUrl(reflector, type, cmpMetadata) {
if (type instanceof StaticSymbol) {
return reflector.resourceUri(type);
}
var /** @type {?} */ moduleId = cmpMetadata.moduleId;
if (typeof moduleId === 'string') {
var /** @type {?} */ 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 \"" + stringifyType(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 ((reflector.importUri(type)));
}
/**
* @param {?} value
* @param {?} targetIdentifiers
* @return {?}
*/
function extractIdentifiers(value, targetIdentifiers) {
visitValue(value, new _CompileValueConverter(), targetIdentifiers);
}
var _CompileValueConverter = (function (_super) {
__extends(_CompileValueConverter, _super);
function _CompileValueConverter() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} value
* @param {?} targetIdentifiers
* @return {?}
*/
_CompileValueConverter.prototype.visitOther = function (value, targetIdentifiers) {
targetIdentifiers.push({ reference: value });
};
return _CompileValueConverter;
}(ValueTransformer));
/**
* @param {?} type
* @return {?}
*/
function stringifyType(type) {
if (type instanceof StaticSymbol) {
return type.name + " in " + type.filePath;
}
else {
return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(type);
}
}
/**
* Indicates that a component is still being loaded in a synchronous compile.
* @param {?} compType
* @return {?}
*/
function componentStillLoadingError(compType) {
var /** @type {?} */ error = Error("Can't compile synchronously as " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(compType) + " is still being loaded!");
((error))[__WEBPACK_IMPORTED_MODULE_0__angular_core__["_55" /* ɵERROR_COMPONENT_TYPE */]] = compType;
return error;
}
/**
* @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
*/
var TypeModifier = {};
TypeModifier.Const = 0;
TypeModifier[TypeModifier.Const] = "Const";
/**
* @abstract
*/
var Type$1 = (function () {
/**
* @param {?=} modifiers
*/
function Type$1(modifiers) {
if (modifiers === void 0) { modifiers = null; }
this.modifiers = modifiers;
if (!modifiers) {
this.modifiers = [];
}
}
/**
* @abstract
* @param {?} visitor
* @param {?} context
* @return {?}
*/
Type$1.prototype.visitType = function (visitor, context) { };
/**
* @param {?} modifier
* @return {?}
*/
Type$1.prototype.hasModifier = function (modifier) { return ((this.modifiers)).indexOf(modifier) !== -1; };
return Type$1;
}());
var BuiltinTypeName = {};
BuiltinTypeName.Dynamic = 0;
BuiltinTypeName.Bool = 1;
BuiltinTypeName.String = 2;
BuiltinTypeName.Int = 3;
BuiltinTypeName.Number = 4;
BuiltinTypeName.Function = 5;
BuiltinTypeName.Inferred = 6;
BuiltinTypeName[BuiltinTypeName.Dynamic] = "Dynamic";
BuiltinTypeName[BuiltinTypeName.Bool] = "Bool";
BuiltinTypeName[BuiltinTypeName.String] = "String";
BuiltinTypeName[BuiltinTypeName.Int] = "Int";
BuiltinTypeName[BuiltinTypeName.Number] = "Number";
BuiltinTypeName[BuiltinTypeName.Function] = "Function";
BuiltinTypeName[BuiltinTypeName.Inferred] = "Inferred";
var BuiltinType = (function (_super) {
__extends(BuiltinType, _super);
/**
* @param {?} name
* @param {?=} modifiers
*/
function BuiltinType(name, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers) || this;
_this.name = name;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
BuiltinType.prototype.visitType = function (visitor, context) {
return visitor.visitBuiltintType(this, context);
};
return BuiltinType;
}(Type$1));
var ExpressionType = (function (_super) {
__extends(ExpressionType, _super);
/**
* @param {?} value
* @param {?=} modifiers
*/
function ExpressionType(value, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers) || this;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ExpressionType.prototype.visitType = function (visitor, context) {
return visitor.visitExpressionType(this, context);
};
return ExpressionType;
}(Type$1));
var ArrayType = (function (_super) {
__extends(ArrayType, _super);
/**
* @param {?} of
* @param {?=} modifiers
*/
function ArrayType(of, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers) || this;
_this.of = of;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ArrayType.prototype.visitType = function (visitor, context) {
return visitor.visitArrayType(this, context);
};
return ArrayType;
}(Type$1));
var MapType = (function (_super) {
__extends(MapType, _super);
/**
* @param {?} valueType
* @param {?=} modifiers
*/
function MapType(valueType, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers) || this;
_this.valueType = valueType || null;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
MapType.prototype.visitType = function (visitor, context) { return visitor.visitMapType(this, context); };
return MapType;
}(Type$1));
var DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic);
var INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred);
var BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool);
var INT_TYPE = new BuiltinType(BuiltinTypeName.Int);
var NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number);
var STRING_TYPE = new BuiltinType(BuiltinTypeName.String);
var FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function);
var BinaryOperator = {};
BinaryOperator.Equals = 0;
BinaryOperator.NotEquals = 1;
BinaryOperator.Identical = 2;
BinaryOperator.NotIdentical = 3;
BinaryOperator.Minus = 4;
BinaryOperator.Plus = 5;
BinaryOperator.Divide = 6;
BinaryOperator.Multiply = 7;
BinaryOperator.Modulo = 8;
BinaryOperator.And = 9;
BinaryOperator.Or = 10;
BinaryOperator.Lower = 11;
BinaryOperator.LowerEquals = 12;
BinaryOperator.Bigger = 13;
BinaryOperator.BiggerEquals = 14;
BinaryOperator[BinaryOperator.Equals] = "Equals";
BinaryOperator[BinaryOperator.NotEquals] = "NotEquals";
BinaryOperator[BinaryOperator.Identical] = "Identical";
BinaryOperator[BinaryOperator.NotIdentical] = "NotIdentical";
BinaryOperator[BinaryOperator.Minus] = "Minus";
BinaryOperator[BinaryOperator.Plus] = "Plus";
BinaryOperator[BinaryOperator.Divide] = "Divide";
BinaryOperator[BinaryOperator.Multiply] = "Multiply";
BinaryOperator[BinaryOperator.Modulo] = "Modulo";
BinaryOperator[BinaryOperator.And] = "And";
BinaryOperator[BinaryOperator.Or] = "Or";
BinaryOperator[BinaryOperator.Lower] = "Lower";
BinaryOperator[BinaryOperator.LowerEquals] = "LowerEquals";
BinaryOperator[BinaryOperator.Bigger] = "Bigger";
BinaryOperator[BinaryOperator.BiggerEquals] = "BiggerEquals";
/**
* @abstract
*/
var Expression = (function () {
/**
* @param {?} type
* @param {?=} sourceSpan
*/
function Expression(type, sourceSpan) {
this.type = type || null;
this.sourceSpan = sourceSpan || null;
}
/**
* @abstract
* @param {?} visitor
* @param {?} context
* @return {?}
*/
Expression.prototype.visitExpression = function (visitor, context) { };
/**
* @param {?} name
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.prop = function (name, sourceSpan) {
return new ReadPropExpr(this, name, null, sourceSpan);
};
/**
* @param {?} index
* @param {?=} type
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.key = function (index, type, sourceSpan) {
return new ReadKeyExpr(this, index, type, sourceSpan);
};
/**
* @param {?} name
* @param {?} params
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.callMethod = function (name, params, sourceSpan) {
return new InvokeMethodExpr(this, name, params, null, sourceSpan);
};
/**
* @param {?} params
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.callFn = function (params, sourceSpan) {
return new InvokeFunctionExpr(this, params, null, sourceSpan);
};
/**
* @param {?} params
* @param {?=} type
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.instantiate = function (params, type, sourceSpan) {
return new InstantiateExpr(this, params, type, sourceSpan);
};
/**
* @param {?} trueCase
* @param {?=} falseCase
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) {
if (falseCase === void 0) { falseCase = null; }
return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.equals = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.notEquals = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.identical = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.notIdentical = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.minus = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.plus = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.divide = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.multiply = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.modulo = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.and = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.or = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.lower = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.lowerEquals = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.bigger = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan);
};
/**
* @param {?} rhs
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.biggerEquals = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
};
/**
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.isBlank = function (sourceSpan) {
// Note: We use equals by purpose here to compare to null and undefined in JS.
// We use the typed null to allow strictNullChecks to narrow types.
return this.equals(TYPED_NULL_EXPR, sourceSpan);
};
/**
* @param {?} type
* @param {?=} sourceSpan
* @return {?}
*/
Expression.prototype.cast = function (type, sourceSpan) {
return new CastExpr(this, type, sourceSpan);
};
/**
* @return {?}
*/
Expression.prototype.toStmt = function () { return new ExpressionStatement(this, null); };
return Expression;
}());
var BuiltinVar = {};
BuiltinVar.This = 0;
BuiltinVar.Super = 1;
BuiltinVar.CatchError = 2;
BuiltinVar.CatchStack = 3;
BuiltinVar[BuiltinVar.This] = "This";
BuiltinVar[BuiltinVar.Super] = "Super";
BuiltinVar[BuiltinVar.CatchError] = "CatchError";
BuiltinVar[BuiltinVar.CatchStack] = "CatchStack";
var ReadVarExpr = (function (_super) {
__extends(ReadVarExpr, _super);
/**
* @param {?} name
* @param {?=} type
* @param {?=} sourceSpan
*/
function ReadVarExpr(name, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
if (typeof name === 'string') {
_this.name = name;
_this.builtin = null;
}
else {
_this.name = null;
_this.builtin = name;
}
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ReadVarExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitReadVarExpr(this, context);
};
/**
* @param {?} value
* @return {?}
*/
ReadVarExpr.prototype.set = function (value) {
if (!this.name) {
throw new Error("Built in variable " + this.builtin + " can not be assigned to.");
}
return new WriteVarExpr(this.name, value, null, this.sourceSpan);
};
return ReadVarExpr;
}(Expression));
var WriteVarExpr = (function (_super) {
__extends(WriteVarExpr, _super);
/**
* @param {?} name
* @param {?} value
* @param {?=} type
* @param {?=} sourceSpan
*/
function WriteVarExpr(name, value, type, sourceSpan) {
var _this = _super.call(this, type || value.type, sourceSpan) || this;
_this.name = name;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
WriteVarExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitWriteVarExpr(this, context);
};
/**
* @param {?=} type
* @param {?=} modifiers
* @return {?}
*/
WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) {
return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
};
return WriteVarExpr;
}(Expression));
var WriteKeyExpr = (function (_super) {
__extends(WriteKeyExpr, _super);
/**
* @param {?} receiver
* @param {?} index
* @param {?} value
* @param {?=} type
* @param {?=} sourceSpan
*/
function WriteKeyExpr(receiver, index, value, type, sourceSpan) {
var _this = _super.call(this, type || value.type, sourceSpan) || this;
_this.receiver = receiver;
_this.index = index;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
WriteKeyExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitWriteKeyExpr(this, context);
};
return WriteKeyExpr;
}(Expression));
var WritePropExpr = (function (_super) {
__extends(WritePropExpr, _super);
/**
* @param {?} receiver
* @param {?} name
* @param {?} value
* @param {?=} type
* @param {?=} sourceSpan
*/
function WritePropExpr(receiver, name, value, type, sourceSpan) {
var _this = _super.call(this, type || value.type, sourceSpan) || this;
_this.receiver = receiver;
_this.name = name;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
WritePropExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitWritePropExpr(this, context);
};
return WritePropExpr;
}(Expression));
var BuiltinMethod = {};
BuiltinMethod.ConcatArray = 0;
BuiltinMethod.SubscribeObservable = 1;
BuiltinMethod.Bind = 2;
BuiltinMethod[BuiltinMethod.ConcatArray] = "ConcatArray";
BuiltinMethod[BuiltinMethod.SubscribeObservable] = "SubscribeObservable";
BuiltinMethod[BuiltinMethod.Bind] = "Bind";
var InvokeMethodExpr = (function (_super) {
__extends(InvokeMethodExpr, _super);
/**
* @param {?} receiver
* @param {?} method
* @param {?} args
* @param {?=} type
* @param {?=} sourceSpan
*/
function InvokeMethodExpr(receiver, method, args, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.receiver = receiver;
_this.args = args;
if (typeof method === 'string') {
_this.name = method;
_this.builtin = null;
}
else {
_this.name = null;
_this.builtin = method;
}
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
InvokeMethodExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitInvokeMethodExpr(this, context);
};
return InvokeMethodExpr;
}(Expression));
var InvokeFunctionExpr = (function (_super) {
__extends(InvokeFunctionExpr, _super);
/**
* @param {?} fn
* @param {?} args
* @param {?=} type
* @param {?=} sourceSpan
*/
function InvokeFunctionExpr(fn, args, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.fn = fn;
_this.args = args;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitInvokeFunctionExpr(this, context);
};
return InvokeFunctionExpr;
}(Expression));
var InstantiateExpr = (function (_super) {
__extends(InstantiateExpr, _super);
/**
* @param {?} classExpr
* @param {?} args
* @param {?=} type
* @param {?=} sourceSpan
*/
function InstantiateExpr(classExpr, args, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.classExpr = classExpr;
_this.args = args;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
InstantiateExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitInstantiateExpr(this, context);
};
return InstantiateExpr;
}(Expression));
var LiteralExpr = (function (_super) {
__extends(LiteralExpr, _super);
/**
* @param {?} value
* @param {?=} type
* @param {?=} sourceSpan
*/
function LiteralExpr(value, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
LiteralExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitLiteralExpr(this, context);
};
return LiteralExpr;
}(Expression));
var ExternalExpr = (function (_super) {
__extends(ExternalExpr, _super);
/**
* @param {?} value
* @param {?=} type
* @param {?=} typeParams
* @param {?=} sourceSpan
*/
function ExternalExpr(value, type, typeParams, sourceSpan) {
if (typeParams === void 0) { typeParams = null; }
var _this = _super.call(this, type, sourceSpan) || this;
_this.value = value;
_this.typeParams = typeParams;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ExternalExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitExternalExpr(this, context);
};
return ExternalExpr;
}(Expression));
var ConditionalExpr = (function (_super) {
__extends(ConditionalExpr, _super);
/**
* @param {?} condition
* @param {?} trueCase
* @param {?=} falseCase
* @param {?=} type
* @param {?=} sourceSpan
*/
function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) {
if (falseCase === void 0) { falseCase = null; }
var _this = _super.call(this, type || trueCase.type, sourceSpan) || this;
_this.condition = condition;
_this.falseCase = falseCase;
_this.trueCase = trueCase;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ConditionalExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitConditionalExpr(this, context);
};
return ConditionalExpr;
}(Expression));
var NotExpr = (function (_super) {
__extends(NotExpr, _super);
/**
* @param {?} condition
* @param {?=} sourceSpan
*/
function NotExpr(condition, sourceSpan) {
var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this;
_this.condition = condition;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
NotExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitNotExpr(this, context);
};
return NotExpr;
}(Expression));
var CastExpr = (function (_super) {
__extends(CastExpr, _super);
/**
* @param {?} value
* @param {?=} type
* @param {?=} sourceSpan
*/
function CastExpr(value, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
CastExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitCastExpr(this, context);
};
return CastExpr;
}(Expression));
var FnParam = (function () {
/**
* @param {?} name
* @param {?=} type
*/
function FnParam(name, type) {
if (type === void 0) { type = null; }
this.name = name;
this.type = type;
}
return FnParam;
}());
var FunctionExpr = (function (_super) {
__extends(FunctionExpr, _super);
/**
* @param {?} params
* @param {?} statements
* @param {?=} type
* @param {?=} sourceSpan
*/
function FunctionExpr(params, statements, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.params = params;
_this.statements = statements;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
FunctionExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitFunctionExpr(this, context);
};
/**
* @param {?} name
* @param {?=} modifiers
* @return {?}
*/
FunctionExpr.prototype.toDeclStmt = function (name, modifiers) {
if (modifiers === void 0) { modifiers = null; }
return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
};
return FunctionExpr;
}(Expression));
var BinaryOperatorExpr = (function (_super) {
__extends(BinaryOperatorExpr, _super);
/**
* @param {?} operator
* @param {?} lhs
* @param {?} rhs
* @param {?=} type
* @param {?=} sourceSpan
*/
function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan) {
var _this = _super.call(this, type || lhs.type, sourceSpan) || this;
_this.operator = operator;
_this.rhs = rhs;
_this.lhs = lhs;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitBinaryOperatorExpr(this, context);
};
return BinaryOperatorExpr;
}(Expression));
var ReadPropExpr = (function (_super) {
__extends(ReadPropExpr, _super);
/**
* @param {?} receiver
* @param {?} name
* @param {?=} type
* @param {?=} sourceSpan
*/
function ReadPropExpr(receiver, name, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.receiver = receiver;
_this.name = name;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ReadPropExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitReadPropExpr(this, context);
};
/**
* @param {?} value
* @return {?}
*/
ReadPropExpr.prototype.set = function (value) {
return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
};
return ReadPropExpr;
}(Expression));
var ReadKeyExpr = (function (_super) {
__extends(ReadKeyExpr, _super);
/**
* @param {?} receiver
* @param {?} index
* @param {?=} type
* @param {?=} sourceSpan
*/
function ReadKeyExpr(receiver, index, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.receiver = receiver;
_this.index = index;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ReadKeyExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitReadKeyExpr(this, context);
};
/**
* @param {?} value
* @return {?}
*/
ReadKeyExpr.prototype.set = function (value) {
return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
};
return ReadKeyExpr;
}(Expression));
var LiteralArrayExpr = (function (_super) {
__extends(LiteralArrayExpr, _super);
/**
* @param {?} entries
* @param {?=} type
* @param {?=} sourceSpan
*/
function LiteralArrayExpr(entries, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.entries = entries;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
LiteralArrayExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitLiteralArrayExpr(this, context);
};
return LiteralArrayExpr;
}(Expression));
var LiteralMapEntry = (function () {
/**
* @param {?} key
* @param {?} value
* @param {?=} quoted
*/
function LiteralMapEntry(key, value, quoted) {
if (quoted === void 0) { quoted = false; }
this.key = key;
this.value = value;
this.quoted = quoted;
}
return LiteralMapEntry;
}());
var LiteralMapExpr = (function (_super) {
__extends(LiteralMapExpr, _super);
/**
* @param {?} entries
* @param {?=} type
* @param {?=} sourceSpan
*/
function LiteralMapExpr(entries, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.entries = entries;
_this.valueType = null;
if (type) {
_this.valueType = type.valueType;
}
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
LiteralMapExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitLiteralMapExpr(this, context);
};
return LiteralMapExpr;
}(Expression));
var CommaExpr = (function (_super) {
__extends(CommaExpr, _super);
/**
* @param {?} parts
* @param {?=} sourceSpan
*/
function CommaExpr(parts, sourceSpan) {
var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this;
_this.parts = parts;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
CommaExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitCommaExpr(this, context);
};
return CommaExpr;
}(Expression));
var THIS_EXPR = new ReadVarExpr(BuiltinVar.This, null, null);
var SUPER_EXPR = new ReadVarExpr(BuiltinVar.Super, null, null);
var CATCH_ERROR_VAR = new ReadVarExpr(BuiltinVar.CatchError, null, null);
var CATCH_STACK_VAR = new ReadVarExpr(BuiltinVar.CatchStack, null, null);
var NULL_EXPR = new LiteralExpr(null, null, null);
var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
var StmtModifier = {};
StmtModifier.Final = 0;
StmtModifier.Private = 1;
StmtModifier[StmtModifier.Final] = "Final";
StmtModifier[StmtModifier.Private] = "Private";
/**
* @abstract
*/
var Statement = (function () {
/**
* @param {?=} modifiers
* @param {?=} sourceSpan
*/
function Statement(modifiers, sourceSpan) {
this.modifiers = modifiers || [];
this.sourceSpan = sourceSpan || null;
}
/**
* @abstract
* @param {?} visitor
* @param {?} context
* @return {?}
*/
Statement.prototype.visitStatement = function (visitor, context) { };
/**
* @param {?} modifier
* @return {?}
*/
Statement.prototype.hasModifier = function (modifier) { return ((this.modifiers)).indexOf(modifier) !== -1; };
return Statement;
}());
var DeclareVarStmt = (function (_super) {
__extends(DeclareVarStmt, _super);
/**
* @param {?} name
* @param {?} value
* @param {?=} type
* @param {?=} modifiers
* @param {?=} sourceSpan
*/
function DeclareVarStmt(name, value, type, modifiers, sourceSpan) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers, sourceSpan) || this;
_this.name = name;
_this.value = value;
_this.type = type || value.type;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
DeclareVarStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitDeclareVarStmt(this, context);
};
return DeclareVarStmt;
}(Statement));
var DeclareFunctionStmt = (function (_super) {
__extends(DeclareFunctionStmt, _super);
/**
* @param {?} name
* @param {?} params
* @param {?} statements
* @param {?=} type
* @param {?=} modifiers
* @param {?=} sourceSpan
*/
function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers, sourceSpan) || this;
_this.name = name;
_this.params = params;
_this.statements = statements;
_this.type = type || null;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitDeclareFunctionStmt(this, context);
};
return DeclareFunctionStmt;
}(Statement));
var ExpressionStatement = (function (_super) {
__extends(ExpressionStatement, _super);
/**
* @param {?} expr
* @param {?=} sourceSpan
*/
function ExpressionStatement(expr, sourceSpan) {
var _this = _super.call(this, null, sourceSpan) || this;
_this.expr = expr;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ExpressionStatement.prototype.visitStatement = function (visitor, context) {
return visitor.visitExpressionStmt(this, context);
};
return ExpressionStatement;
}(Statement));
var ReturnStatement = (function (_super) {
__extends(ReturnStatement, _super);
/**
* @param {?} value
* @param {?=} sourceSpan
*/
function ReturnStatement(value, sourceSpan) {
var _this = _super.call(this, null, sourceSpan) || this;
_this.value = value;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ReturnStatement.prototype.visitStatement = function (visitor, context) {
return visitor.visitReturnStmt(this, context);
};
return ReturnStatement;
}(Statement));
var AbstractClassPart = (function () {
/**
* @param {?} type
* @param {?} modifiers
*/
function AbstractClassPart(type, modifiers) {
this.modifiers = modifiers;
if (!modifiers) {
this.modifiers = [];
}
this.type = type || null;
}
/**
* @param {?} modifier
* @return {?}
*/
AbstractClassPart.prototype.hasModifier = function (modifier) { return ((this.modifiers)).indexOf(modifier) !== -1; };
return AbstractClassPart;
}());
var ClassField = (function (_super) {
__extends(ClassField, _super);
/**
* @param {?} name
* @param {?=} type
* @param {?=} modifiers
*/
function ClassField(name, type, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, type, modifiers) || this;
_this.name = name;
return _this;
}
return ClassField;
}(AbstractClassPart));
var ClassMethod = (function (_super) {
__extends(ClassMethod, _super);
/**
* @param {?} name
* @param {?} params
* @param {?} body
* @param {?=} type
* @param {?=} modifiers
*/
function ClassMethod(name, params, body, type, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, type, modifiers) || this;
_this.name = name;
_this.params = params;
_this.body = body;
return _this;
}
return ClassMethod;
}(AbstractClassPart));
var ClassGetter = (function (_super) {
__extends(ClassGetter, _super);
/**
* @param {?} name
* @param {?} body
* @param {?=} type
* @param {?=} modifiers
*/
function ClassGetter(name, body, type, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, type, modifiers) || this;
_this.name = name;
_this.body = body;
return _this;
}
return ClassGetter;
}(AbstractClassPart));
var ClassStmt = (function (_super) {
__extends(ClassStmt, _super);
/**
* @param {?} name
* @param {?} parent
* @param {?} fields
* @param {?} getters
* @param {?} constructorMethod
* @param {?} methods
* @param {?=} modifiers
* @param {?=} sourceSpan
*/
function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers, sourceSpan) || this;
_this.name = name;
_this.parent = parent;
_this.fields = fields;
_this.getters = getters;
_this.constructorMethod = constructorMethod;
_this.methods = methods;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ClassStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitDeclareClassStmt(this, context);
};
return ClassStmt;
}(Statement));
var IfStmt = (function (_super) {
__extends(IfStmt, _super);
/**
* @param {?} condition
* @param {?} trueCase
* @param {?=} falseCase
* @param {?=} sourceSpan
*/
function IfStmt(condition, trueCase, falseCase, sourceSpan) {
if (falseCase === void 0) { falseCase = []; }
var _this = _super.call(this, null, sourceSpan) || this;
_this.condition = condition;
_this.trueCase = trueCase;
_this.falseCase = falseCase;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
IfStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitIfStmt(this, context);
};
return IfStmt;
}(Statement));
var TryCatchStmt = (function (_super) {
__extends(TryCatchStmt, _super);
/**
* @param {?} bodyStmts
* @param {?} catchStmts
* @param {?=} sourceSpan
*/
function TryCatchStmt(bodyStmts, catchStmts, sourceSpan) {
var _this = _super.call(this, null, sourceSpan) || this;
_this.bodyStmts = bodyStmts;
_this.catchStmts = catchStmts;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
TryCatchStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitTryCatchStmt(this, context);
};
return TryCatchStmt;
}(Statement));
var ThrowStmt = (function (_super) {
__extends(ThrowStmt, _super);
/**
* @param {?} error
* @param {?=} sourceSpan
*/
function ThrowStmt(error, sourceSpan) {
var _this = _super.call(this, null, sourceSpan) || this;
_this.error = error;
return _this;
}
/**
* @param {?} visitor
* @param {?} context
* @return {?}
*/
ThrowStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitThrowStmt(this, context);
};
return ThrowStmt;
}(Statement));
var AstTransformer$1 = (function () {
function AstTransformer$1() {
}
/**
* @param {?} expr
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.transformExpr = function (expr, context) { return expr; };
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.transformStmt = function (stmt, context) { return stmt; };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitReadVarExpr = function (ast, context) { return this.transformExpr(ast, context); };
/**
* @param {?} expr
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitWriteVarExpr = function (expr, context) {
return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
};
/**
* @param {?} expr
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitWriteKeyExpr = function (expr, context) {
return this.transformExpr(new WriteKeyExpr(expr.receiver.visitExpression(this, context), expr.index.visitExpression(this, context), expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
};
/**
* @param {?} expr
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitWritePropExpr = function (expr, context) {
return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitInvokeMethodExpr = function (ast, context) {
var /** @type {?} */ method = ast.builtin || ast.name;
return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), /** @type {?} */ ((method)), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitInvokeFunctionExpr = function (ast, context) {
return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitInstantiateExpr = function (ast, context) {
return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitLiteralExpr = function (ast, context) { return this.transformExpr(ast, context); };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitExternalExpr = function (ast, context) {
return this.transformExpr(ast, context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitConditionalExpr = function (ast, context) {
return this.transformExpr(new ConditionalExpr(ast.condition.visitExpression(this, context), ast.trueCase.visitExpression(this, context), /** @type {?} */ ((ast.falseCase)).visitExpression(this, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitNotExpr = function (ast, context) {
return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitCastExpr = function (ast, context) {
return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitFunctionExpr = function (ast, context) {
return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitBinaryOperatorExpr = function (ast, context) {
return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitReadPropExpr = function (ast, context) {
return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitReadKeyExpr = function (ast, context) {
return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitLiteralArrayExpr = function (ast, context) {
return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitLiteralMapExpr = function (ast, context) {
var _this = this;
var /** @type {?} */ entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); });
var /** @type {?} */ mapType = new MapType(ast.valueType, null);
return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitCommaExpr = function (ast, context) {
return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
};
/**
* @param {?} exprs
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitAllExpressions = function (exprs, context) {
var _this = this;
return exprs.map(function (expr) { return expr.visitExpression(_this, context); });
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitDeclareVarStmt = function (stmt, context) {
return this.transformStmt(new DeclareVarStmt(stmt.name, stmt.value.visitExpression(this, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context);
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitDeclareFunctionStmt = function (stmt, context) {
return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context);
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitExpressionStmt = function (stmt, context) {
return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan), context);
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitReturnStmt = function (stmt, context) {
return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan), context);
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitDeclareClassStmt = function (stmt, context) {
var _this = this;
var /** @type {?} */ parent = ((stmt.parent)).visitExpression(this, context);
var /** @type {?} */ getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); });
var /** @type {?} */ ctorMethod = stmt.constructorMethod &&
new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
var /** @type {?} */ methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); });
return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context);
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitIfStmt = function (stmt, context) {
return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan), context);
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitTryCatchStmt = function (stmt, context) {
return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan), context);
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitThrowStmt = function (stmt, context) {
return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan), context);
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitCommentStmt = function (stmt, context) {
return this.transformStmt(stmt, context);
};
/**
* @param {?} stmts
* @param {?} context
* @return {?}
*/
AstTransformer$1.prototype.visitAllStatements = function (stmts, context) {
var _this = this;
return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); });
};
return AstTransformer$1;
}());
var RecursiveAstVisitor$1 = (function () {
function RecursiveAstVisitor$1() {
}
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitReadVarExpr = function (ast, context) { return ast; };
/**
* @param {?} expr
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitWriteVarExpr = function (expr, context) {
expr.value.visitExpression(this, context);
return expr;
};
/**
* @param {?} expr
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitWriteKeyExpr = function (expr, context) {
expr.receiver.visitExpression(this, context);
expr.index.visitExpression(this, context);
expr.value.visitExpression(this, context);
return expr;
};
/**
* @param {?} expr
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitWritePropExpr = function (expr, context) {
expr.receiver.visitExpression(this, context);
expr.value.visitExpression(this, context);
return expr;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitInvokeMethodExpr = function (ast, context) {
ast.receiver.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitInvokeFunctionExpr = function (ast, context) {
ast.fn.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitInstantiateExpr = function (ast, context) {
ast.classExpr.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitLiteralExpr = function (ast, context) { return ast; };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitExternalExpr = function (ast, context) { return ast; };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitConditionalExpr = function (ast, context) {
ast.condition.visitExpression(this, context);
ast.trueCase.visitExpression(this, context); /** @type {?} */
((ast.falseCase)).visitExpression(this, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitNotExpr = function (ast, context) {
ast.condition.visitExpression(this, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitCastExpr = function (ast, context) {
ast.value.visitExpression(this, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitFunctionExpr = function (ast, context) {
this.visitAllStatements(ast.statements, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitBinaryOperatorExpr = function (ast, context) {
ast.lhs.visitExpression(this, context);
ast.rhs.visitExpression(this, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitReadPropExpr = function (ast, context) {
ast.receiver.visitExpression(this, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitReadKeyExpr = function (ast, context) {
ast.receiver.visitExpression(this, context);
ast.index.visitExpression(this, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitLiteralArrayExpr = function (ast, context) {
this.visitAllExpressions(ast.entries, context);
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitLiteralMapExpr = function (ast, context) {
var _this = this;
ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); });
return ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitCommaExpr = function (ast, context) {
this.visitAllExpressions(ast.parts, context);
};
/**
* @param {?} exprs
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitAllExpressions = function (exprs, context) {
var _this = this;
exprs.forEach(function (expr) { return expr.visitExpression(_this, context); });
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitDeclareVarStmt = function (stmt, context) {
stmt.value.visitExpression(this, context);
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitDeclareFunctionStmt = function (stmt, context) {
this.visitAllStatements(stmt.statements, context);
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitExpressionStmt = function (stmt, context) {
stmt.expr.visitExpression(this, context);
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitReturnStmt = function (stmt, context) {
stmt.value.visitExpression(this, context);
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitDeclareClassStmt = function (stmt, context) {
var _this = this;
((stmt.parent)).visitExpression(this, context);
stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); });
if (stmt.constructorMethod) {
this.visitAllStatements(stmt.constructorMethod.body, context);
}
stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); });
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitIfStmt = function (stmt, context) {
stmt.condition.visitExpression(this, context);
this.visitAllStatements(stmt.trueCase, context);
this.visitAllStatements(stmt.falseCase, context);
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitTryCatchStmt = function (stmt, context) {
this.visitAllStatements(stmt.bodyStmts, context);
this.visitAllStatements(stmt.catchStmts, context);
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitThrowStmt = function (stmt, context) {
stmt.error.visitExpression(this, context);
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitCommentStmt = function (stmt, context) { return stmt; };
/**
* @param {?} stmts
* @param {?} context
* @return {?}
*/
RecursiveAstVisitor$1.prototype.visitAllStatements = function (stmts, context) {
var _this = this;
stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); });
};
return RecursiveAstVisitor$1;
}());
/**
* @param {?} stmts
* @return {?}
*/
function findReadVarNames(stmts) {
var /** @type {?} */ visitor = new _ReadVarVisitor();
visitor.visitAllStatements(stmts, null);
return visitor.varNames;
}
var _ReadVarVisitor = (function (_super) {
__extends(_ReadVarVisitor, _super);
function _ReadVarVisitor() {
var _this = _super.apply(this, arguments) || this;
_this.varNames = new Set();
return _this;
}
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
_ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
// Don't descend into nested functions
return stmt;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
_ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
// Don't descend into nested classes
return stmt;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
_ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) {
if (ast.name) {
this.varNames.add(ast.name);
}
return null;
};
return _ReadVarVisitor;
}(RecursiveAstVisitor$1));
/**
* @param {?} stmt
* @param {?} sourceSpan
* @return {?}
*/
function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) {
if (!sourceSpan) {
return stmt;
}
var /** @type {?} */ transformer = new _ApplySourceSpanTransformer(sourceSpan);
return stmt.visitStatement(transformer, null);
}
/**
* @param {?} expr
* @param {?} sourceSpan
* @return {?}
*/
function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) {
if (!sourceSpan) {
return expr;
}
var /** @type {?} */ transformer = new _ApplySourceSpanTransformer(sourceSpan);
return expr.visitExpression(transformer, null);
}
var _ApplySourceSpanTransformer = (function (_super) {
__extends(_ApplySourceSpanTransformer, _super);
/**
* @param {?} sourceSpan
*/
function _ApplySourceSpanTransformer(sourceSpan) {
var _this = _super.call(this) || this;
_this.sourceSpan = sourceSpan;
return _this;
}
/**
* @param {?} obj
* @return {?}
*/
_ApplySourceSpanTransformer.prototype._clone = function (obj) {
var /** @type {?} */ clone = Object.create(obj.constructor.prototype);
for (var /** @type {?} */ prop in obj) {
clone[prop] = obj[prop];
}
return clone;
};
/**
* @param {?} expr
* @param {?} context
* @return {?}
*/
_ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) {
if (!expr.sourceSpan) {
expr = this._clone(expr);
expr.sourceSpan = this.sourceSpan;
}
return expr;
};
/**
* @param {?} stmt
* @param {?} context
* @return {?}
*/
_ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) {
if (!stmt.sourceSpan) {
stmt = this._clone(stmt);
stmt.sourceSpan = this.sourceSpan;
}
return stmt;
};
return _ApplySourceSpanTransformer;
}(AstTransformer$1));
/**
* @param {?} name
* @param {?=} type
* @param {?=} sourceSpan
* @return {?}
*/
function variable(name, type, sourceSpan) {
return new ReadVarExpr(name, type, sourceSpan);
}
/**
* @param {?} id
* @param {?=} typeParams
* @param {?=} sourceSpan
* @return {?}
*/
function importExpr(id, typeParams, sourceSpan) {
if (typeParams === void 0) { typeParams = null; }
return new ExternalExpr(id, null, typeParams, sourceSpan);
}
/**
* @param {?} id
* @param {?=} typeParams
* @param {?=} typeModifiers
* @return {?}
*/
function importType(id, typeParams, typeModifiers) {
if (typeParams === void 0) { typeParams = null; }
if (typeModifiers === void 0) { typeModifiers = null; }
return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
}
/**
* @param {?} expr
* @param {?=} typeModifiers
* @return {?}
*/
function expressionType(expr, typeModifiers) {
if (typeModifiers === void 0) { typeModifiers = null; }
return expr != null ? ((new ExpressionType(expr, typeModifiers))) : null;
}
/**
* @param {?} values
* @param {?=} type
* @param {?=} sourceSpan
* @return {?}
*/
function literalArr(values, type, sourceSpan) {
return new LiteralArrayExpr(values, type, sourceSpan);
}
/**
* @param {?} values
* @param {?=} type
* @param {?=} quoted
* @return {?}
*/
function literalMap(values, type, quoted) {
if (type === void 0) { type = null; }
if (quoted === void 0) { quoted = false; }
return new LiteralMapExpr(values.map(function (entry) { return new LiteralMapEntry(entry[0], entry[1], quoted); }), type, null);
}
/**
* @param {?} expr
* @param {?=} sourceSpan
* @return {?}
*/
function not(expr, sourceSpan) {
return new NotExpr(expr, sourceSpan);
}
/**
* @param {?} params
* @param {?} body
* @param {?=} type
* @param {?=} sourceSpan
* @return {?}
*/
function fn(params, body, type, sourceSpan) {
return new FunctionExpr(params, body, type, sourceSpan);
}
/**
* @param {?} value
* @param {?=} type
* @param {?=} sourceSpan
* @return {?}
*/
function literal(value, type, sourceSpan) {
return new LiteralExpr(value, type, sourceSpan);
}
/**
* @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
*/
/**
* Create a new class stmts based on the given data.
* @param {?} config
* @return {?}
*/
function createClassStmt(config) {
var /** @type {?} */ parentArgs = config.parentArgs || [];
var /** @type {?} */ superCtorStmts = config.parent ? [SUPER_EXPR.callFn(parentArgs).toStmt()] : [];
var /** @type {?} */ builder = concatClassBuilderParts(Array.isArray(config.builders) ? config.builders : [config.builders]);
var /** @type {?} */ ctor = new ClassMethod(null, config.ctorParams || [], superCtorStmts.concat(builder.ctorStmts));
return new ClassStmt(config.name, config.parent || null, builder.fields, builder.getters, ctor, builder.methods, config.modifiers || [], config.sourceSpan);
}
/**
* @param {?} builders
* @return {?}
*/
function concatClassBuilderParts(builders) {
return {
fields: [].concat.apply([], ((builders.map((function (builder) { return builder.fields || []; }))))),
methods: [].concat.apply([], ((builders.map(function (builder) { return builder.methods || []; })))),
getters: [].concat.apply([], ((builders.map(function (builder) { return builder.getters || []; })))),
ctorStmts: [].concat.apply([], ((builders.map(function (builder) { return builder.ctorStmts || []; })))),
};
}
/**
* @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
*/
var QUOTED_KEYS = '$quoted$';
/**
* @param {?} value
* @param {?=} type
* @return {?}
*/
function convertValueToOutputAst(value, type) {
if (type === void 0) { type = null; }
return visitValue(value, new _ValueOutputAstTransformer(), type);
}
var _ValueOutputAstTransformer = (function () {
function _ValueOutputAstTransformer() {
}
/**
* @param {?} arr
* @param {?} type
* @return {?}
*/
_ValueOutputAstTransformer.prototype.visitArray = function (arr, type) {
var _this = this;
return literalArr(arr.map(function (value) { return visitValue(value, _this, null); }), type);
};
/**
* @param {?} map
* @param {?} type
* @return {?}
*/
_ValueOutputAstTransformer.prototype.visitStringMap = function (map, type) {
var _this = this;
var /** @type {?} */ entries = [];
var /** @type {?} */ quotedSet = new Set(map && map[QUOTED_KEYS]);
Object.keys(map).forEach(function (key) {
entries.push(new LiteralMapEntry(key, visitValue(map[key], _this, null), quotedSet.has(key)));
});
return new LiteralMapExpr(entries, type);
};
/**
* @param {?} value
* @param {?} type
* @return {?}
*/
_ValueOutputAstTransformer.prototype.visitPrimitive = function (value, type) { return literal(value, type); };
/**
* @param {?} value
* @param {?} type
* @return {?}
*/
_ValueOutputAstTransformer.prototype.visitOther = function (value, type) {
if (value instanceof Expression) {
return value;
}
else {
return importExpr({ reference: value });
}
};
return _ValueOutputAstTransformer;
}());
/**
* @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
*/
/**
* This is currently not read, but will probably be used in the future.
* We keep it as we already pass it through all the rigth places...
*/
var ComponentFactoryDependency = (function () {
/**
* @param {?} compType
*/
function ComponentFactoryDependency(compType) {
this.compType = compType;
}
return ComponentFactoryDependency;
}());
var NgModuleCompileResult = (function () {
/**
* @param {?} statements
* @param {?} ngModuleFactoryVar
* @param {?} dependencies
*/
function NgModuleCompileResult(statements, ngModuleFactoryVar, dependencies) {
this.statements = statements;
this.ngModuleFactoryVar = ngModuleFactoryVar;
this.dependencies = dependencies;
}
return NgModuleCompileResult;
}());
var NgModuleCompiler = (function () {
function NgModuleCompiler() {
}
/**
* @param {?} ngModuleMeta
* @param {?} extraProviders
* @return {?}
*/
NgModuleCompiler.prototype.compile = function (ngModuleMeta, extraProviders) {
var /** @type {?} */ sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type);
var /** @type {?} */ deps = [];
var /** @type {?} */ bootstrapComponentFactories = [];
var /** @type {?} */ entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents.map(function (entryComponent) {
if (ngModuleMeta.bootstrapComponents.some(function (id) { return id.reference === entryComponent.componentType; })) {
bootstrapComponentFactories.push({ reference: entryComponent.componentFactory });
}
deps.push(new ComponentFactoryDependency(entryComponent.componentType));
return { reference: entryComponent.componentFactory };
});
var /** @type {?} */ builder = new _InjectorBuilder(ngModuleMeta, entryComponentFactories, bootstrapComponentFactories, sourceSpan);
var /** @type {?} */ providerParser = new NgModuleProviderAnalyzer(ngModuleMeta, extraProviders, sourceSpan);
providerParser.parse().forEach(function (provider) { return builder.addProvider(provider); });
var /** @type {?} */ injectorClass = builder.build();
var /** @type {?} */ ngModuleFactoryVar = identifierName(ngModuleMeta.type) + "NgFactory";
var /** @type {?} */ ngModuleFactoryStmt = variable(ngModuleFactoryVar)
.set(importExpr(createIdentifier(Identifiers.NgModuleFactory))
.instantiate([variable(injectorClass.name), importExpr(ngModuleMeta.type)], importType(createIdentifier(Identifiers.NgModuleFactory), [/** @type {?} */ ((importType(ngModuleMeta.type)))], [TypeModifier.Const])))
.toDeclStmt(null, [StmtModifier.Final]);
var /** @type {?} */ stmts = [injectorClass, ngModuleFactoryStmt];
if (ngModuleMeta.id) {
var /** @type {?} */ registerFactoryStmt = importExpr(createIdentifier(Identifiers.RegisterModuleFactoryFn))
.callFn([literal(ngModuleMeta.id), variable(ngModuleFactoryVar)])
.toStmt();
stmts.push(registerFactoryStmt);
}
return new NgModuleCompileResult(stmts, ngModuleFactoryVar, deps);
};
return NgModuleCompiler;
}());
NgModuleCompiler.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
NgModuleCompiler.ctorParameters = function () { return []; };
var _InjectorBuilder = (function () {
/**
* @param {?} _ngModuleMeta
* @param {?} _entryComponentFactories
* @param {?} _bootstrapComponentFactories
* @param {?} _sourceSpan
*/
function _InjectorBuilder(_ngModuleMeta, _entryComponentFactories, _bootstrapComponentFactories, _sourceSpan) {
this._ngModuleMeta = _ngModuleMeta;
this._entryComponentFactories = _entryComponentFactories;
this._bootstrapComponentFactories = _bootstrapComponentFactories;
this._sourceSpan = _sourceSpan;
this.fields = [];
this.getters = [];
this.methods = [];
this.ctorStmts = [];
this._lazyProps = new Map();
this._tokens = [];
this._instances = new Map();
this._createStmts = [];
this._destroyStmts = [];
}
/**
* @param {?} resolvedProvider
* @return {?}
*/
_InjectorBuilder.prototype.addProvider = function (resolvedProvider) {
var _this = this;
var /** @type {?} */ providerValueExpressions = resolvedProvider.providers.map(function (provider) { return _this._getProviderValue(provider); });
var /** @type {?} */ propName = "_" + tokenName(resolvedProvider.token) + "_" + this._instances.size;
var /** @type {?} */ instance = this._createProviderProperty(propName, resolvedProvider, providerValueExpressions, resolvedProvider.multiProvider, resolvedProvider.eager);
if (resolvedProvider.lifecycleHooks.indexOf(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnDestroy) !== -1) {
var /** @type {?} */ callNgOnDestroy = instance.callMethod('ngOnDestroy', []);
if (!resolvedProvider.eager) {
callNgOnDestroy = ((this._lazyProps.get(instance.name))).and(callNgOnDestroy);
}
this._destroyStmts.push(callNgOnDestroy.toStmt());
}
this._tokens.push(resolvedProvider.token);
this._instances.set(tokenReference(resolvedProvider.token), instance);
};
/**
* @return {?}
*/
_InjectorBuilder.prototype.build = function () {
var _this = this;
var /** @type {?} */ getMethodStmts = this._tokens.map(function (token) {
var /** @type {?} */ providerExpr = ((_this._instances.get(tokenReference(token))));
return new IfStmt(InjectMethodVars.token.identical(createDiTokenExpression(token)), [new ReturnStatement(providerExpr)]);
});
var /** @type {?} */ methods = [
new ClassMethod('createInternal', [], this._createStmts.concat(new ReturnStatement(/** @type {?} */ ((this._instances.get(this._ngModuleMeta.type.reference))))), importType(this._ngModuleMeta.type)),
new ClassMethod('getInternal', [
new FnParam(/** @type {?} */ ((InjectMethodVars.token.name)), DYNAMIC_TYPE),
new FnParam(/** @type {?} */ ((InjectMethodVars.notFoundResult.name)), DYNAMIC_TYPE)
], getMethodStmts.concat([new ReturnStatement(InjectMethodVars.notFoundResult)]), DYNAMIC_TYPE),
new ClassMethod('destroyInternal', [], this._destroyStmts),
];
var /** @type {?} */ parentArgs = [
variable(InjectorProps.parent.name),
literalArr(this._entryComponentFactories.map(function (componentFactory) { return importExpr(componentFactory); })),
literalArr(this._bootstrapComponentFactories.map(function (componentFactory) { return importExpr(componentFactory); }))
];
var /** @type {?} */ injClassName = identifierName(this._ngModuleMeta.type) + "Injector";
return createClassStmt({
name: injClassName,
ctorParams: [new FnParam(InjectorProps.parent.name, importType(createIdentifier(Identifiers.Injector)))],
parent: importExpr(createIdentifier(Identifiers.NgModuleInjector), [/** @type {?} */ ((importType(this._ngModuleMeta.type)))]),
parentArgs: parentArgs,
builders: [{ methods: methods }, this]
});
};
/**
* @param {?} provider
* @return {?}
*/
_InjectorBuilder.prototype._getProviderValue = function (provider) {
var _this = this;
var /** @type {?} */ result;
if (provider.useExisting != null) {
result = this._getDependency({ token: provider.useExisting });
}
else if (provider.useFactory != null) {
var /** @type {?} */ deps = provider.deps || provider.useFactory.diDeps;
var /** @type {?} */ depsExpr = deps.map(function (dep) { return _this._getDependency(dep); });
result = importExpr(provider.useFactory).callFn(depsExpr);
}
else if (provider.useClass != null) {
var /** @type {?} */ deps = provider.deps || provider.useClass.diDeps;
var /** @type {?} */ depsExpr = deps.map(function (dep) { return _this._getDependency(dep); });
result =
importExpr(provider.useClass).instantiate(depsExpr, importType(provider.useClass));
}
else {
result = convertValueToOutputAst(provider.useValue);
}
return result;
};
/**
* @param {?} propName
* @param {?} provider
* @param {?} providerValueExpressions
* @param {?} isMulti
* @param {?} isEager
* @return {?}
*/
_InjectorBuilder.prototype._createProviderProperty = function (propName, provider, providerValueExpressions, isMulti, isEager) {
var /** @type {?} */ resolvedProviderValueExpr;
var /** @type {?} */ type;
if (isMulti) {
resolvedProviderValueExpr = literalArr(providerValueExpressions);
type = new ArrayType(DYNAMIC_TYPE);
}
else {
resolvedProviderValueExpr = providerValueExpressions[0];
type = ((providerValueExpressions[0].type));
}
if (!type) {
type = DYNAMIC_TYPE;
}
if (isEager) {
this.fields.push(new ClassField(propName, type));
this._createStmts.push(THIS_EXPR.prop(propName).set(resolvedProviderValueExpr).toStmt());
}
else {
var /** @type {?} */ internalFieldProp = THIS_EXPR.prop("_" + propName);
this.fields.push(new ClassField(internalFieldProp.name, type));
// Note: Equals is important for JS so that it also checks the undefined case!
var /** @type {?} */ getterStmts = [
new IfStmt(internalFieldProp.isBlank(), [internalFieldProp.set(resolvedProviderValueExpr).toStmt()]),
new ReturnStatement(internalFieldProp)
];
this.getters.push(new ClassGetter(propName, getterStmts, type));
this._lazyProps.set(propName, internalFieldProp);
}
return THIS_EXPR.prop(propName);
};
/**
* @param {?} dep
* @return {?}
*/
_InjectorBuilder.prototype._getDependency = function (dep) {
var /** @type {?} */ result = ((null));
if (dep.isValue) {
result = literal(dep.value);
}
if (!dep.isSkipSelf) {
if (dep.token) {
if (tokenReference(dep.token) === resolveIdentifier(Identifiers.Injector)) {
result = THIS_EXPR;
}
else if (tokenReference(dep.token) === resolveIdentifier(Identifiers.ComponentFactoryResolver)) {
result = THIS_EXPR.prop('componentFactoryResolver');
}
}
if (!result) {
result = ((this._instances.get(tokenReference(/** @type {?} */ ((dep.token))))));
}
}
if (!result) {
var /** @type {?} */ args = [createDiTokenExpression(/** @type {?} */ ((dep.token)))];
if (dep.isOptional) {
args.push(NULL_EXPR);
}
result = InjectorProps.parent.callMethod('get', args);
}
return result;
};
return _InjectorBuilder;
}());
/**
* @param {?} token
* @return {?}
*/
function createDiTokenExpression(token) {
if (token.value != null) {
return literal(token.value);
}
else {
return importExpr(/** @type {?} */ ((token.identifier)));
}
}
var InjectorProps = (function () {
function InjectorProps() {
}
return InjectorProps;
}());
InjectorProps.parent = THIS_EXPR.prop('parent');
var InjectMethodVars = (function () {
function InjectMethodVars() {
}
return InjectMethodVars;
}());
InjectMethodVars.token = variable('token');
InjectMethodVars.notFoundResult = variable('notFoundResult');
/**
* @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
*/
// https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
var VERSION$1 = 3;
var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
var SourceMapGenerator = (function () {
/**
* @param {?=} file
*/
function SourceMapGenerator(file) {
if (file === void 0) { file = null; }
this.file = file;
this.sourcesContent = new Map();
this.lines = [];
this.lastCol0 = 0;
this.hasMappings = false;
}
/**
* @param {?} url
* @param {?=} content
* @return {?}
*/
SourceMapGenerator.prototype.addSource = function (url, content) {
if (content === void 0) { content = null; }
if (!this.sourcesContent.has(url)) {
this.sourcesContent.set(url, content);
}
return this;
};
/**
* @return {?}
*/
SourceMapGenerator.prototype.addLine = function () {
this.lines.push([]);
this.lastCol0 = 0;
return this;
};
/**
* @param {?} col0
* @param {?=} sourceUrl
* @param {?=} sourceLine0
* @param {?=} sourceCol0
* @return {?}
*/
SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) {
if (!this.currentLine) {
throw new Error("A line must be added before mappings can be added");
}
if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) {
throw new Error("Unknown source file \"" + sourceUrl + "\"");
}
if (col0 == null) {
throw new Error("The column in the generated code must be provided");
}
if (col0 < this.lastCol0) {
throw new Error("Mapping should be added in output order");
}
if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) {
throw new Error("The source location must be provided when a source url is provided");
}
this.hasMappings = true;
this.lastCol0 = col0;
this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 });
return this;
};
Object.defineProperty(SourceMapGenerator.prototype, "currentLine", {
/**
* @return {?}
*/
get: function () { return this.lines.slice(-1)[0]; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
SourceMapGenerator.prototype.toJSON = function () {
var _this = this;
if (!this.hasMappings) {
return null;
}
var /** @type {?} */ sourcesIndex = new Map();
var /** @type {?} */ sources = [];
var /** @type {?} */ sourcesContent = [];
Array.from(this.sourcesContent.keys()).forEach(function (url, i) {
sourcesIndex.set(url, i);
sources.push(url);
sourcesContent.push(_this.sourcesContent.get(url) || null);
});
var /** @type {?} */ mappings = '';
var /** @type {?} */ lastCol0 = 0;
var /** @type {?} */ lastSourceIndex = 0;
var /** @type {?} */ lastSourceLine0 = 0;
var /** @type {?} */ lastSourceCol0 = 0;
this.lines.forEach(function (segments) {
lastCol0 = 0;
mappings += segments
.map(function (segment) {
// zero-based starting column of the line in the generated code
var /** @type {?} */ segAsStr = toBase64VLQ(segment.col0 - lastCol0);
lastCol0 = segment.col0;
if (segment.sourceUrl != null) {
// zero-based index into the “sources” list
segAsStr +=
toBase64VLQ(/** @type {?} */ ((sourcesIndex.get(segment.sourceUrl))) - lastSourceIndex);
lastSourceIndex = ((sourcesIndex.get(segment.sourceUrl)));
// the zero-based starting line in the original source
segAsStr += toBase64VLQ(/** @type {?} */ ((segment.sourceLine0)) - lastSourceLine0);
lastSourceLine0 = ((segment.sourceLine0));
// the zero-based starting column in the original source
segAsStr += toBase64VLQ(/** @type {?} */ ((segment.sourceCol0)) - lastSourceCol0);
lastSourceCol0 = ((segment.sourceCol0));
}
return segAsStr;
})
.join(',');
mappings += ';';
});
mappings = mappings.slice(0, -1);
return {
'file': this.file || '',
'version': VERSION$1,
'sourceRoot': '',
'sources': sources,
'sourcesContent': sourcesContent,
'mappings': mappings,
};
};
/**
* @return {?}
*/
SourceMapGenerator.prototype.toJsComment = function () {
return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
'';
};
return SourceMapGenerator;
}());
/**
* @param {?} value
* @return {?}
*/
function toBase64String(value) {
var /** @type {?} */ b64 = '';
value = utf8Encode(value);
for (var /** @type {?} */ i = 0; i < value.length;) {
var /** @type {?} */ i1 = value.charCodeAt(i++);
var /** @type {?} */ i2 = value.charCodeAt(i++);
var /** @type {?} */ i3 = value.charCodeAt(i++);
b64 += toBase64Digit(i1 >> 2);
b64 += toBase64Digit(((i1 & 3) << 4) | (isNaN(i2) ? 0 : i2 >> 4));
b64 += isNaN(i2) ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 >> 6));
b64 += isNaN(i2) || isNaN(i3) ? '=' : toBase64Digit(i3 & 63);
}
return b64;
}
/**
* @param {?} value
* @return {?}
*/
function toBase64VLQ(value) {
value = value < 0 ? ((-value) << 1) + 1 : value << 1;
var /** @type {?} */ out = '';
do {
var /** @type {?} */ digit = value & 31;
value = value >> 5;
if (value > 0) {
digit = digit | 32;
}
out += toBase64Digit(digit);
} while (value > 0);
return out;
}
var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
/**
* @param {?} value
* @return {?}
*/
function toBase64Digit(value) {
if (value < 0 || value >= 64) {
throw new Error("Can only encode value in the range [0, 63]");
}
return B64_DIGITS[value];
}
/**
* @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
*/
var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
var _INDENT_WITH = ' ';
var CATCH_ERROR_VAR$1 = variable('error', null, null);
var CATCH_STACK_VAR$1 = variable('stack', null, null);
/**
* @abstract
*/
var _EmittedLine = (function () {
/**
* @param {?} indent
*/
function _EmittedLine(indent) {
this.indent = indent;
this.parts = [];
this.srcSpans = [];
}
return _EmittedLine;
}());
var EmitterVisitorContext = (function () {
/**
* @param {?} _exportedVars
* @param {?} _indent
*/
function EmitterVisitorContext(_exportedVars, _indent) {
this._exportedVars = _exportedVars;
this._indent = _indent;
this._classes = [];
this._lines = [new _EmittedLine(_indent)];
}
/**
* @param {?} exportedVars
* @return {?}
*/
EmitterVisitorContext.createRoot = function (exportedVars) {
return new EmitterVisitorContext(exportedVars, 0);
};
Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", {
/**
* @return {?}
*/
get: function () { return this._lines[this._lines.length - 1]; },
enumerable: true,
configurable: true
});
/**
* @param {?} varName
* @return {?}
*/
EmitterVisitorContext.prototype.isExportedVar = function (varName) { return this._exportedVars.indexOf(varName) !== -1; };
/**
* @param {?=} from
* @param {?=} lastPart
* @return {?}
*/
EmitterVisitorContext.prototype.println = function (from, lastPart) {
if (lastPart === void 0) { lastPart = ''; }
this.print(from || null, lastPart, true);
};
/**
* @return {?}
*/
EmitterVisitorContext.prototype.lineIsEmpty = function () { return this._currentLine.parts.length === 0; };
/**
* @param {?} from
* @param {?} part
* @param {?=} newLine
* @return {?}
*/
EmitterVisitorContext.prototype.print = function (from, part, newLine) {
if (newLine === void 0) { newLine = false; }
if (part.length > 0) {
this._currentLine.parts.push(part);
this._currentLine.srcSpans.push(from && from.sourceSpan || null);
}
if (newLine) {
this._lines.push(new _EmittedLine(this._indent));
}
};
/**
* @return {?}
*/
EmitterVisitorContext.prototype.removeEmptyLastLine = function () {
if (this.lineIsEmpty()) {
this._lines.pop();
}
};
/**
* @return {?}
*/
EmitterVisitorContext.prototype.incIndent = function () {
this._indent++;
this._currentLine.indent = this._indent;
};
/**
* @return {?}
*/
EmitterVisitorContext.prototype.decIndent = function () {
this._indent--;
this._currentLine.indent = this._indent;
};
/**
* @param {?} clazz
* @return {?}
*/
EmitterVisitorContext.prototype.pushClass = function (clazz) { this._classes.push(clazz); };
/**
* @return {?}
*/
EmitterVisitorContext.prototype.popClass = function () { return ((this._classes.pop())); };
Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", {
/**
* @return {?}
*/
get: function () {
return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
EmitterVisitorContext.prototype.toSource = function () {
return this.sourceLines
.map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; })
.join('\n');
};
/**
* @param {?} sourceFilePath
* @param {?} genFilePath
* @param {?=} startsAtLine
* @return {?}
*/
EmitterVisitorContext.prototype.toSourceMapGenerator = function (sourceFilePath, genFilePath, startsAtLine) {
if (startsAtLine === void 0) { startsAtLine = 0; }
var /** @type {?} */ map = new SourceMapGenerator(genFilePath);
var /** @type {?} */ firstOffsetMapped = false;
var /** @type {?} */ mapFirstOffsetIfNeeded = function () {
if (!firstOffsetMapped) {
// Add a single space so that tools won't try to load the file from disk.
// Note: We are using virtual urls like `ng:///`, so we have to
// provide a content here.
map.addSource(sourceFilePath, ' ').addMapping(0, sourceFilePath, 0, 0);
firstOffsetMapped = true;
}
};
for (var /** @type {?} */ i = 0; i < startsAtLine; i++) {
map.addLine();
mapFirstOffsetIfNeeded();
}
this.sourceLines.forEach(function (line, lineIdx) {
map.addLine();
var /** @type {?} */ spans = line.srcSpans;
var /** @type {?} */ parts = line.parts;
var /** @type {?} */ col0 = line.indent * _INDENT_WITH.length;
var /** @type {?} */ spanIdx = 0;
// skip leading parts without source spans
while (spanIdx < spans.length && !spans[spanIdx]) {
col0 += parts[spanIdx].length;
spanIdx++;
}
if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) {
firstOffsetMapped = true;
}
else {
mapFirstOffsetIfNeeded();
}
while (spanIdx < spans.length) {
var /** @type {?} */ span = ((spans[spanIdx]));
var /** @type {?} */ source = span.start.file;
var /** @type {?} */ sourceLine = span.start.line;
var /** @type {?} */ sourceCol = span.start.col;
map.addSource(source.url, source.content)
.addMapping(col0, source.url, sourceLine, sourceCol);
col0 += parts[spanIdx].length;
spanIdx++;
// assign parts without span or the same span to the previous segment
while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
col0 += parts[spanIdx].length;
spanIdx++;
}
}
});
return map;
};
Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", {
/**
* @return {?}
*/
get: function () {
if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
return this._lines.slice(0, -1);
}
return this._lines;
},
enumerable: true,
configurable: true
});
return EmitterVisitorContext;
}());
/**
* @abstract
*/
var AbstractEmitterVisitor = (function () {
/**
* @param {?} _escapeDollarInStrings
*/
function AbstractEmitterVisitor(_escapeDollarInStrings) {
this._escapeDollarInStrings = _escapeDollarInStrings;
}
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) {
stmt.expr.visitExpression(this, ctx);
ctx.println(stmt, ';');
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) {
ctx.print(stmt, "return ");
stmt.value.visitExpression(this, ctx);
ctx.println(stmt, ';');
return null;
};
/**
* @abstract
* @param {?} ast
* @param {?} context
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitCastExpr = function (ast, context) { };
/**
* @abstract
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) { };
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) {
ctx.print(stmt, "if (");
stmt.condition.visitExpression(this, ctx);
ctx.print(stmt, ") {");
var /** @type {?} */ hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
if (stmt.trueCase.length <= 1 && !hasElseCase) {
ctx.print(stmt, " ");
this.visitAllStatements(stmt.trueCase, ctx);
ctx.removeEmptyLastLine();
ctx.print(stmt, " ");
}
else {
ctx.println();
ctx.incIndent();
this.visitAllStatements(stmt.trueCase, ctx);
ctx.decIndent();
if (hasElseCase) {
ctx.println(stmt, "} else {");
ctx.incIndent();
this.visitAllStatements(stmt.falseCase, ctx);
ctx.decIndent();
}
}
ctx.println(stmt, "}");
return null;
};
/**
* @abstract
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) { };
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) {
ctx.print(stmt, "throw ");
stmt.error.visitExpression(this, ctx);
ctx.println(stmt, ";");
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitCommentStmt = function (stmt, ctx) {
var /** @type {?} */ lines = stmt.comment.split('\n');
lines.forEach(function (line) { ctx.println(stmt, "// " + line); });
return null;
};
/**
* @abstract
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) { };
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) {
var /** @type {?} */ lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) {
ctx.print(expr, '(');
}
ctx.print(expr, expr.name + " = ");
expr.value.visitExpression(this, ctx);
if (!lineWasEmpty) {
ctx.print(expr, ')');
}
return null;
};
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) {
var /** @type {?} */ lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) {
ctx.print(expr, '(');
}
expr.receiver.visitExpression(this, ctx);
ctx.print(expr, "[");
expr.index.visitExpression(this, ctx);
ctx.print(expr, "] = ");
expr.value.visitExpression(this, ctx);
if (!lineWasEmpty) {
ctx.print(expr, ')');
}
return null;
};
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) {
var /** @type {?} */ lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) {
ctx.print(expr, '(');
}
expr.receiver.visitExpression(this, ctx);
ctx.print(expr, "." + expr.name + " = ");
expr.value.visitExpression(this, ctx);
if (!lineWasEmpty) {
ctx.print(expr, ')');
}
return null;
};
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) {
expr.receiver.visitExpression(this, ctx);
var /** @type {?} */ name = expr.name;
if (expr.builtin != null) {
name = this.getBuiltinMethodName(expr.builtin);
if (name == null) {
// some builtins just mean to skip the call.
return null;
}
}
ctx.print(expr, "." + name + "(");
this.visitAllExpressions(expr.args, ctx, ",");
ctx.print(expr, ")");
return null;
};
/**
* @abstract
* @param {?} method
* @return {?}
*/
AbstractEmitterVisitor.prototype.getBuiltinMethodName = function (method) { };
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
expr.fn.visitExpression(this, ctx);
ctx.print(expr, "(");
this.visitAllExpressions(expr.args, ctx, ',');
ctx.print(expr, ")");
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
var /** @type {?} */ varName = ((ast.name));
if (ast.builtin != null) {
switch (ast.builtin) {
case BuiltinVar.Super:
varName = 'super';
break;
case BuiltinVar.This:
varName = 'this';
break;
case BuiltinVar.CatchError:
varName = ((CATCH_ERROR_VAR$1.name));
break;
case BuiltinVar.CatchStack:
varName = ((CATCH_STACK_VAR$1.name));
break;
default:
throw new Error("Unknown builtin variable " + ast.builtin);
}
}
ctx.print(ast, varName);
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
ctx.print(ast, "new ");
ast.classExpr.visitExpression(this, ctx);
ctx.print(ast, "(");
this.visitAllExpressions(ast.args, ctx, ',');
ctx.print(ast, ")");
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
var /** @type {?} */ value = ast.value;
if (typeof value === 'string') {
ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
}
else {
ctx.print(ast, "" + value);
}
return null;
};
/**
* @abstract
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) { };
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) {
ctx.print(ast, "(");
ast.condition.visitExpression(this, ctx);
ctx.print(ast, '? ');
ast.trueCase.visitExpression(this, ctx);
ctx.print(ast, ': '); /** @type {?} */
((ast.falseCase)).visitExpression(this, ctx);
ctx.print(ast, ")");
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) {
ctx.print(ast, '!');
ast.condition.visitExpression(this, ctx);
return null;
};
/**
* @abstract
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) { };
/**
* @abstract
* @param {?} stmt
* @param {?} context
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) { };
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
var /** @type {?} */ opStr;
switch (ast.operator) {
case BinaryOperator.Equals:
opStr = '==';
break;
case BinaryOperator.Identical:
opStr = '===';
break;
case BinaryOperator.NotEquals:
opStr = '!=';
break;
case BinaryOperator.NotIdentical:
opStr = '!==';
break;
case BinaryOperator.And:
opStr = '&&';
break;
case BinaryOperator.Or:
opStr = '||';
break;
case BinaryOperator.Plus:
opStr = '+';
break;
case BinaryOperator.Minus:
opStr = '-';
break;
case BinaryOperator.Divide:
opStr = '/';
break;
case BinaryOperator.Multiply:
opStr = '*';
break;
case BinaryOperator.Modulo:
opStr = '%';
break;
case BinaryOperator.Lower:
opStr = '<';
break;
case BinaryOperator.LowerEquals:
opStr = '<=';
break;
case BinaryOperator.Bigger:
opStr = '>';
break;
case BinaryOperator.BiggerEquals:
opStr = '>=';
break;
default:
throw new Error("Unknown operator " + ast.operator);
}
ctx.print(ast, "(");
ast.lhs.visitExpression(this, ctx);
ctx.print(ast, " " + opStr + " ");
ast.rhs.visitExpression(this, ctx);
ctx.print(ast, ")");
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) {
ast.receiver.visitExpression(this, ctx);
ctx.print(ast, ".");
ctx.print(ast, ast.name);
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) {
ast.receiver.visitExpression(this, ctx);
ctx.print(ast, "[");
ast.index.visitExpression(this, ctx);
ctx.print(ast, "]");
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
var /** @type {?} */ useNewLine = ast.entries.length > 1;
ctx.print(ast, "[", useNewLine);
ctx.incIndent();
this.visitAllExpressions(ast.entries, ctx, ',', useNewLine);
ctx.decIndent();
ctx.print(ast, "]", useNewLine);
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) {
var _this = this;
var /** @type {?} */ useNewLine = ast.entries.length > 1;
ctx.print(ast, "{", useNewLine);
ctx.incIndent();
this.visitAllObjects(function (entry) {
ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ": ");
entry.value.visitExpression(_this, ctx);
}, ast.entries, ctx, ',', useNewLine);
ctx.decIndent();
ctx.print(ast, "}", useNewLine);
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) {
ctx.print(ast, '(');
this.visitAllExpressions(ast.parts, ctx, ',');
ctx.print(ast, ')');
return null;
};
/**
* @param {?} expressions
* @param {?} ctx
* @param {?} separator
* @param {?=} newLine
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator, newLine) {
var _this = this;
if (newLine === void 0) { newLine = false; }
this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator, newLine);
};
/**
* @template T
* @param {?} handler
* @param {?} expressions
* @param {?} ctx
* @param {?} separator
* @param {?=} newLine
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator, newLine) {
if (newLine === void 0) { newLine = false; }
for (var /** @type {?} */ i = 0; i < expressions.length; i++) {
if (i > 0) {
ctx.print(null, separator, newLine);
}
handler(expressions[i]);
}
if (newLine) {
ctx.println();
}
};
/**
* @param {?} statements
* @param {?} ctx
* @return {?}
*/
AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) {
var _this = this;
statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); });
};
return AbstractEmitterVisitor;
}());
/**
* @param {?} input
* @param {?} escapeDollar
* @param {?=} alwaysQuote
* @return {?}
*/
function escapeIdentifier(input, escapeDollar, alwaysQuote) {
if (alwaysQuote === void 0) { alwaysQuote = true; }
if (input == null) {
return null;
}
var /** @type {?} */ body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () {
var match = [];
for (var _i = 0; _i < arguments.length; _i++) {
match[_i] = arguments[_i];
}
if (match[0] == '$') {
return escapeDollar ? '\\$' : '$';
}
else if (match[0] == '\n') {
return '\\n';
}
else if (match[0] == '\r') {
return '\\r';
}
else {
return "\\" + match[0];
}
});
var /** @type {?} */ requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
return requiresQuotes ? "'" + body + "'" : body;
}
/**
* @param {?} count
* @return {?}
*/
function _createIndent(count) {
var /** @type {?} */ res = '';
for (var /** @type {?} */ i = 0; i < count; i++) {
res += _INDENT_WITH;
}
return res;
}
/**
* @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
*/
var _debugFilePath = '/debug/lib';
/**
* @param {?} ast
* @return {?}
*/
function debugOutputAstAsTypeScript(ast) {
var /** @type {?} */ converter = new _TsEmitterVisitor(_debugFilePath, {
/**
* @param {?} filePath
* @param {?} containingFilePath
* @return {?}
*/
fileNameToModuleName: function (filePath, containingFilePath) { return filePath; },
/**
* @param {?} symbol
* @return {?}
*/
getImportAs: function (symbol) { return null; },
getTypeArity: function (symbol) { return null; }
});
var /** @type {?} */ ctx = EmitterVisitorContext.createRoot([]);
var /** @type {?} */ asts = Array.isArray(ast) ? ast : [ast];
asts.forEach(function (ast) {
if (ast instanceof Statement) {
ast.visitStatement(converter, ctx);
}
else if (ast instanceof Expression) {
ast.visitExpression(converter, ctx);
}
else if (ast instanceof Type$1) {
ast.visitType(converter, ctx);
}
else {
throw new Error("Don't know how to print debug info for " + ast);
}
});
return ctx.toSource();
}
var TypeScriptEmitter = (function () {
/**
* @param {?} _importResolver
*/
function TypeScriptEmitter(_importResolver) {
this._importResolver = _importResolver;
}
/**
* @param {?} srcFilePath
* @param {?} genFilePath
* @param {?} stmts
* @param {?} exportedVars
* @param {?=} preamble
* @return {?}
*/
TypeScriptEmitter.prototype.emitStatements = function (srcFilePath, genFilePath, stmts, exportedVars, preamble) {
var _this = this;
if (preamble === void 0) { preamble = ''; }
var /** @type {?} */ converter = new _TsEmitterVisitor(genFilePath, this._importResolver);
var /** @type {?} */ ctx = EmitterVisitorContext.createRoot(exportedVars);
converter.visitAllStatements(stmts, ctx);
var /** @type {?} */ preambleLines = preamble ? preamble.split('\n') : [];
converter.reexports.forEach(function (reexports, exportedFilePath) {
var /** @type {?} */ reexportsCode = reexports.map(function (reexport) { return reexport.name + " as " + reexport.as; }).join(',');
preambleLines.push("export {" + reexportsCode + "} from '" + _this._importResolver.fileNameToModuleName(exportedFilePath, genFilePath) + "';");
});
converter.importsWithPrefixes.forEach(function (prefix, importedFilePath) {
// Note: can't write the real word for import as it screws up system.js auto detection...
preambleLines.push("imp" +
("ort * as " + prefix + " from '" + _this._importResolver.fileNameToModuleName(importedFilePath, genFilePath) + "';"));
});
var /** @type {?} */ sm = ctx.toSourceMapGenerator(srcFilePath, genFilePath, preambleLines.length).toJsComment();
var /** @type {?} */ lines = preambleLines.concat([ctx.toSource(), sm]);
if (sm) {
// always add a newline at the end, as some tools have bugs without it.
lines.push('');
}
return lines.join('\n');
};
return TypeScriptEmitter;
}());
var _TsEmitterVisitor = (function (_super) {
__extends(_TsEmitterVisitor, _super);
/**
* @param {?} _genFilePath
* @param {?} _importResolver
*/
function _TsEmitterVisitor(_genFilePath, _importResolver) {
var _this = _super.call(this, false) || this;
_this._genFilePath = _genFilePath;
_this._importResolver = _importResolver;
_this.typeExpression = 0;
_this.importsWithPrefixes = new Map();
_this.reexports = new Map();
return _this;
}
/**
* @param {?} t
* @param {?} ctx
* @param {?=} defaultType
* @return {?}
*/
_TsEmitterVisitor.prototype.visitType = function (t, ctx, defaultType) {
if (defaultType === void 0) { defaultType = 'any'; }
if (t) {
this.typeExpression++;
t.visitType(this, ctx);
this.typeExpression--;
}
else {
ctx.print(null, defaultType);
}
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
var /** @type {?} */ value = ast.value;
if (value == null && ast.type != INFERRED_TYPE) {
ctx.print(ast, "(" + value + " as any)");
return null;
}
return _super.prototype.visitLiteralExpr.call(this, ast, ctx);
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
if (ast.entries.length === 0) {
ctx.print(ast, '(');
}
var /** @type {?} */ result = _super.prototype.visitLiteralArrayExpr.call(this, ast, ctx);
if (ast.entries.length === 0) {
ctx.print(ast, ' as any[])');
}
return result;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
this._visitIdentifier(ast.value, ast.typeParams, ctx);
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
if (ctx.isExportedVar(stmt.name) && stmt.value instanceof ExternalExpr && !stmt.type) {
// check for a reexport
var _a = this._resolveStaticSymbol(stmt.value.value), name = _a.name, filePath = _a.filePath, members = _a.members;
if (((members)).length === 0 && filePath !== this._genFilePath) {
var /** @type {?} */ reexports = this.reexports.get(filePath);
if (!reexports) {
reexports = [];
this.reexports.set(filePath, reexports);
}
reexports.push({ name: name, as: stmt.name });
return null;
}
}
if (ctx.isExportedVar(stmt.name)) {
ctx.print(stmt, "export ");
}
if (stmt.hasModifier(StmtModifier.Final)) {
ctx.print(stmt, "const");
}
else {
ctx.print(stmt, "var");
}
ctx.print(stmt, " " + stmt.name);
this._printColonType(stmt.type, ctx);
ctx.print(stmt, " = ");
stmt.value.visitExpression(this, ctx);
ctx.println(stmt, ";");
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
ctx.print(ast, "(<"); /** @type {?} */
((ast.type)).visitType(this, ctx);
ctx.print(ast, ">");
ast.value.visitExpression(this, ctx);
ctx.print(ast, ")");
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
ctx.print(ast, "new ");
this.typeExpression++;
ast.classExpr.visitExpression(this, ctx);
this.typeExpression--;
ctx.print(ast, "(");
this.visitAllExpressions(ast.args, ctx, ',');
ctx.print(ast, ")");
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
var _this = this;
ctx.pushClass(stmt);
if (ctx.isExportedVar(stmt.name)) {
ctx.print(stmt, "export ");
}
ctx.print(stmt, "class " + stmt.name);
if (stmt.parent != null) {
ctx.print(stmt, " extends ");
this.typeExpression++;
stmt.parent.visitExpression(this, ctx);
this.typeExpression--;
}
ctx.println(stmt, " {");
ctx.incIndent();
stmt.fields.forEach(function (field) { return _this._visitClassField(field, ctx); });
if (stmt.constructorMethod != null) {
this._visitClassConstructor(stmt, ctx);
}
stmt.getters.forEach(function (getter) { return _this._visitClassGetter(getter, ctx); });
stmt.methods.forEach(function (method) { return _this._visitClassMethod(method, ctx); });
ctx.decIndent();
ctx.println(stmt, "}");
ctx.popClass();
return null;
};
/**
* @param {?} field
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype._visitClassField = function (field, ctx) {
if (field.hasModifier(StmtModifier.Private)) {
// comment out as a workaround for #10967
ctx.print(null, "/*private*/ ");
}
ctx.print(null, field.name);
this._printColonType(field.type, ctx);
ctx.println(null, ";");
};
/**
* @param {?} getter
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype._visitClassGetter = function (getter, ctx) {
if (getter.hasModifier(StmtModifier.Private)) {
ctx.print(null, "private ");
}
ctx.print(null, "get " + getter.name + "()");
this._printColonType(getter.type, ctx);
ctx.println(null, " {");
ctx.incIndent();
this.visitAllStatements(getter.body, ctx);
ctx.decIndent();
ctx.println(null, "}");
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
ctx.print(stmt, "constructor(");
this._visitParams(stmt.constructorMethod.params, ctx);
ctx.println(stmt, ") {");
ctx.incIndent();
this.visitAllStatements(stmt.constructorMethod.body, ctx);
ctx.decIndent();
ctx.println(stmt, "}");
};
/**
* @param {?} method
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype._visitClassMethod = function (method, ctx) {
if (method.hasModifier(StmtModifier.Private)) {
ctx.print(null, "private ");
}
ctx.print(null, method.name + "(");
this._visitParams(method.params, ctx);
ctx.print(null, ")");
this._printColonType(method.type, ctx, 'void');
ctx.println(null, " {");
ctx.incIndent();
this.visitAllStatements(method.body, ctx);
ctx.decIndent();
ctx.println(null, "}");
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
ctx.print(ast, "(");
this._visitParams(ast.params, ctx);
ctx.print(ast, ")");
this._printColonType(ast.type, ctx, 'void');
ctx.println(ast, " => {");
ctx.incIndent();
this.visitAllStatements(ast.statements, ctx);
ctx.decIndent();
ctx.print(ast, "}");
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
if (ctx.isExportedVar(stmt.name)) {
ctx.print(stmt, "export ");
}
ctx.print(stmt, "function " + stmt.name + "(");
this._visitParams(stmt.params, ctx);
ctx.print(stmt, ")");
this._printColonType(stmt.type, ctx, 'void');
ctx.println(stmt, " {");
ctx.incIndent();
this.visitAllStatements(stmt.statements, ctx);
ctx.decIndent();
ctx.println(stmt, "}");
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
ctx.println(stmt, "try {");
ctx.incIndent();
this.visitAllStatements(stmt.bodyStmts, ctx);
ctx.decIndent();
ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
ctx.incIndent();
var /** @type {?} */ catchStmts = [/** @type {?} */ (CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack', null)).toDeclStmt(null, [
StmtModifier.Final
]))].concat(stmt.catchStmts);
this.visitAllStatements(catchStmts, ctx);
ctx.decIndent();
ctx.println(stmt, "}");
return null;
};
/**
* @param {?} type
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitBuiltintType = function (type, ctx) {
var /** @type {?} */ typeStr;
switch (type.name) {
case BuiltinTypeName.Bool:
typeStr = 'boolean';
break;
case BuiltinTypeName.Dynamic:
typeStr = 'any';
break;
case BuiltinTypeName.Function:
typeStr = 'Function';
break;
case BuiltinTypeName.Number:
typeStr = 'number';
break;
case BuiltinTypeName.Int:
typeStr = 'number';
break;
case BuiltinTypeName.String:
typeStr = 'string';
break;
default:
throw new Error("Unsupported builtin type " + type.name);
}
ctx.print(null, typeStr);
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitExpressionType = function (ast, ctx) {
ast.value.visitExpression(this, ctx);
return null;
};
/**
* @param {?} type
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitArrayType = function (type, ctx) {
this.visitType(type.of, ctx);
ctx.print(null, "[]");
return null;
};
/**
* @param {?} type
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype.visitMapType = function (type, ctx) {
ctx.print(null, "{[key: string]:");
this.visitType(type.valueType, ctx);
ctx.print(null, "}");
return null;
};
/**
* @param {?} method
* @return {?}
*/
_TsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
var /** @type {?} */ name;
switch (method) {
case BuiltinMethod.ConcatArray:
name = 'concat';
break;
case BuiltinMethod.SubscribeObservable:
name = 'subscribe';
break;
case BuiltinMethod.Bind:
name = 'bind';
break;
default:
throw new Error("Unknown builtin method: " + method);
}
return name;
};
/**
* @param {?} params
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype._visitParams = function (params, ctx) {
var _this = this;
this.visitAllObjects(function (param) {
ctx.print(null, param.name);
_this._printColonType(param.type, ctx);
}, params, ctx, ',');
};
/**
* @param {?} value
* @return {?}
*/
_TsEmitterVisitor.prototype._resolveStaticSymbol = function (value) {
var /** @type {?} */ reference = value.reference;
if (!(reference instanceof StaticSymbol)) {
throw new Error("Internal error: unknown identifier " + JSON.stringify(value));
}
var /** @type {?} */ arity = this._importResolver.getTypeArity(reference) || undefined;
var /** @type {?} */ importReference = this._importResolver.getImportAs(reference) || reference;
return {
name: importReference.name,
filePath: importReference.filePath,
members: importReference.members, arity: arity
};
};
/**
* @param {?} value
* @param {?} typeParams
* @param {?} ctx
* @return {?}
*/
_TsEmitterVisitor.prototype._visitIdentifier = function (value, typeParams, ctx) {
var _this = this;
var _a = this._resolveStaticSymbol(value), name = _a.name, filePath = _a.filePath, members = _a.members, arity = _a.arity;
if (filePath != this._genFilePath) {
var /** @type {?} */ prefix = this.importsWithPrefixes.get(filePath);
if (prefix == null) {
prefix = "import" + this.importsWithPrefixes.size;
this.importsWithPrefixes.set(filePath, prefix);
}
ctx.print(null, prefix + ".");
}
if (((members)).length) {
ctx.print(null, name);
ctx.print(null, '.');
ctx.print(null, /** @type {?} */ ((members)).join('.'));
}
else {
ctx.print(null, name);
}
if (this.typeExpression > 0) {
// If we are in a type expression that refers to a generic type then supply
// the required type parameters. If there were not enough type parameters
// supplied, supply any as the type. Outside a type expression the reference
// should not supply type parameters and be treated as a simple value reference
// to the constructor function itself.
var /** @type {?} */ suppliedParameters = (typeParams && typeParams.length) || 0;
var /** @type {?} */ additionalParameters = (arity || 0) - suppliedParameters;
if (suppliedParameters > 0 || additionalParameters > 0) {
ctx.print(null, "<");
if (suppliedParameters > 0) {
this.visitAllObjects(function (type) { return type.visitType(_this, ctx); }, /** @type {?} */ ((typeParams)), ctx, ',');
}
if (additionalParameters > 0) {
for (var /** @type {?} */ i = 0; i < additionalParameters; i++) {
if (i > 0 || suppliedParameters > 0)
ctx.print(null, ',');
ctx.print(null, 'any');
}
}
ctx.print(null, ">");
}
}
};
/**
* @param {?} type
* @param {?} ctx
* @param {?=} defaultType
* @return {?}
*/
_TsEmitterVisitor.prototype._printColonType = function (type, ctx, defaultType) {
if (type !== INFERRED_TYPE) {
ctx.print(null, ':');
this.visitType(type, ctx, defaultType);
}
};
return _TsEmitterVisitor;
}(AbstractEmitterVisitor));
/**
* @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
*/
// =================================================================================================
// =================================================================================================
// =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
// =================================================================================================
// =================================================================================================
//
// DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW!
// Reach out to mprobst for details.
//
// =================================================================================================
/** Map from tagName|propertyName SecurityContext. Properties applying to all tags use '*'. */
var SECURITY_SCHEMA = {};
/**
* @param {?} ctx
* @param {?} specs
* @return {?}
*/
function registerContext(ctx, specs) {
for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) {
var spec = specs_1[_i];
SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
}
}
// Case is insignificant below, all element and attribute names are lower-cased for lookup.
registerContext(__WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].HTML, [
'iframe|srcdoc',
'*|innerHTML',
'*|outerHTML',
]);
registerContext(__WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].STYLE, ['*|style']);
// NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them.
registerContext(__WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].URL, [
'*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href',
'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action',
'img|src', 'img|srcset', 'input|src', 'ins|cite', 'q|cite',
'source|src', 'source|srcset', 'track|src', 'video|poster', 'video|src',
]);
registerContext(__WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].RESOURCE_URL, [
'applet|code',
'applet|codebase',
'base|href',
'embed|src',
'frame|src',
'head|profile',
'html|manifest',
'iframe|src',
'link|href',
'media|src',
'object|codebase',
'object|data',
'script|src',
]);
/**
* @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
*/
var BOOLEAN = 'boolean';
var NUMBER = 'number';
var STRING = 'string';
var OBJECT = 'object';
/**
* This array represents the DOM schema. It encodes inheritance, properties, and events.
*
* ## Overview
*
* Each line represents one kind of element. The `element_inheritance` and properties are joined
* using `element_inheritance|properties` syntax.
*
* ## Element Inheritance
*
* The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`.
* Here the individual elements are separated by `,` (commas). Every element in the list
* has identical properties.
*
* An `element` may inherit additional properties from `parentElement` If no `^parentElement` is
* specified then `""` (blank) element is assumed.
*
* NOTE: The blank element inherits from root `[Element]` element, the super element of all
* elements.
*
* NOTE an element prefix such as `:svg:` has no special meaning to the schema.
*
* ## Properties
*
* Each element has a set of properties separated by `,` (commas). Each property can be prefixed
* by a special character designating its type:
*
* - (no prefix): property is a string.
* - `*`: property represents an event.
* - `!`: property is a boolean.
* - `#`: property is a number.
* - `%`: property is an object.
*
* ## Query
*
* The class creates an internal squas representation which allows to easily answer the query of
* if a given property exist on a given element.
*
* NOTE: We don't yet support querying for types or events.
* NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder,
* see dom_element_schema_registry_spec.ts
*/
// =================================================================================================
// =================================================================================================
// =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
// =================================================================================================
// =================================================================================================
//
// DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW!
//
// Newly added properties must be security reviewed and assigned an appropriate SecurityContext in
// dom_security_schema.ts. Reach out to mprobst & rjamet for details.
//
// =================================================================================================
var SCHEMA = [
'[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop',
'[HTMLElement]^[Element]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate',
'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate',
'media^[HTMLElement]|!autoplay,!controls,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,#playbackRate,preload,src,%srcObject,#volume',
':svg:^[HTMLElement]|*abort,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex',
':svg:graphics^:svg:|',
':svg:animation^:svg:|*begin,*end,*repeat',
':svg:geometry^:svg:|',
':svg:componentTransferFunction^:svg:|',
':svg:gradient^:svg:|',
':svg:textContent^:svg:graphics|',
':svg:textPositioning^:svg:textContent|',
'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username',
'area^[HTMLElement]|alt,coords,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,search,shape,target,username',
'audio^media|',
'br^[HTMLElement]|clear',
'base^[HTMLElement]|href,target',
'body^[HTMLElement]|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink',
'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
'canvas^[HTMLElement]|#height,#width',
'content^[HTMLElement]|select',
'dl^[HTMLElement]|!compact',
'datalist^[HTMLElement]|',
'details^[HTMLElement]|!open',
'dialog^[HTMLElement]|!open,returnValue',
'dir^[HTMLElement]|!compact',
'div^[HTMLElement]|align',
'embed^[HTMLElement]|align,height,name,src,type,width',
'fieldset^[HTMLElement]|!disabled,name',
'font^[HTMLElement]|color,face,size',
'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
'hr^[HTMLElement]|align,color,!noShade,size,width',
'head^[HTMLElement]|',
'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
'html^[HTMLElement]|version',
'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
'input^[HTMLElement]|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width',
'keygen^[HTMLElement]|!autofocus,challenge,!disabled,keytype,name',
'li^[HTMLElement]|type,#value',
'label^[HTMLElement]|htmlFor',
'legend^[HTMLElement]|align',
'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,rel,%relList,rev,%sizes,target,type',
'map^[HTMLElement]|name',
'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
'menu^[HTMLElement]|!compact',
'meta^[HTMLElement]|content,httpEquiv,name,scheme',
'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
'ins,del^[HTMLElement]|cite,dateTime',
'ol^[HTMLElement]|!compact,!reversed,#start,type',
'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
'optgroup^[HTMLElement]|!disabled,label',
'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
'p^[HTMLElement]|align',
'param^[HTMLElement]|name,type,value,valueType',
'picture^[HTMLElement]|',
'pre^[HTMLElement]|#width',
'progress^[HTMLElement]|#max,#value',
'q,blockquote,cite^[HTMLElement]|',
'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
'shadow^[HTMLElement]|',
'source^[HTMLElement]|media,sizes,src,srcset,type',
'span^[HTMLElement]|',
'style^[HTMLElement]|!disabled,media,type',
'caption^[HTMLElement]|align',
'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
'template^[HTMLElement]|',
'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
'title^[HTMLElement]|text',
'track^[HTMLElement]|!default,kind,label,src,srclang',
'ul^[HTMLElement]|!compact,type',
'unknown^[HTMLElement]|',
'video^media|#height,poster,#width',
':svg:a^:svg:graphics|',
':svg:animate^:svg:animation|',
':svg:animateMotion^:svg:animation|',
':svg:animateTransform^:svg:animation|',
':svg:circle^:svg:geometry|',
':svg:clipPath^:svg:graphics|',
':svg:cursor^:svg:|',
':svg:defs^:svg:graphics|',
':svg:desc^:svg:|',
':svg:discard^:svg:|',
':svg:ellipse^:svg:geometry|',
':svg:feBlend^:svg:|',
':svg:feColorMatrix^:svg:|',
':svg:feComponentTransfer^:svg:|',
':svg:feComposite^:svg:|',
':svg:feConvolveMatrix^:svg:|',
':svg:feDiffuseLighting^:svg:|',
':svg:feDisplacementMap^:svg:|',
':svg:feDistantLight^:svg:|',
':svg:feDropShadow^:svg:|',
':svg:feFlood^:svg:|',
':svg:feFuncA^:svg:componentTransferFunction|',
':svg:feFuncB^:svg:componentTransferFunction|',
':svg:feFuncG^:svg:componentTransferFunction|',
':svg:feFuncR^:svg:componentTransferFunction|',
':svg:feGaussianBlur^:svg:|',
':svg:feImage^:svg:|',
':svg:feMerge^:svg:|',
':svg:feMergeNode^:svg:|',
':svg:feMorphology^:svg:|',
':svg:feOffset^:svg:|',
':svg:fePointLight^:svg:|',
':svg:feSpecularLighting^:svg:|',
':svg:feSpotLight^:svg:|',
':svg:feTile^:svg:|',
':svg:feTurbulence^:svg:|',
':svg:filter^:svg:|',
':svg:foreignObject^:svg:graphics|',
':svg:g^:svg:graphics|',
':svg:image^:svg:graphics|',
':svg:line^:svg:geometry|',
':svg:linearGradient^:svg:gradient|',
':svg:mpath^:svg:|',
':svg:marker^:svg:|',
':svg:mask^:svg:|',
':svg:metadata^:svg:|',
':svg:path^:svg:geometry|',
':svg:pattern^:svg:|',
':svg:polygon^:svg:geometry|',
':svg:polyline^:svg:geometry|',
':svg:radialGradient^:svg:gradient|',
':svg:rect^:svg:geometry|',
':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
':svg:script^:svg:|type',
':svg:set^:svg:animation|',
':svg:stop^:svg:|',
':svg:style^:svg:|!disabled,media,title,type',
':svg:switch^:svg:graphics|',
':svg:symbol^:svg:|',
':svg:tspan^:svg:textPositioning|',
':svg:text^:svg:textPositioning|',
':svg:textPath^:svg:textContent|',
':svg:title^:svg:|',
':svg:use^:svg:graphics|',
':svg:view^:svg:|#zoomAndPan',
'data^[HTMLElement]|value',
'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
'summary^[HTMLElement]|',
'time^[HTMLElement]|dateTime',
];
var _ATTR_TO_PROP = {
'class': 'className',
'for': 'htmlFor',
'formaction': 'formAction',
'innerHtml': 'innerHTML',
'readonly': 'readOnly',
'tabindex': 'tabIndex',
};
var DomElementSchemaRegistry = (function (_super) {
__extends(DomElementSchemaRegistry, _super);
function DomElementSchemaRegistry() {
var _this = _super.call(this) || this;
_this._schema = {};
SCHEMA.forEach(function (encodedType) {
var type = {};
var _a = encodedType.split('|'), strType = _a[0], strProperties = _a[1];
var properties = strProperties.split(',');
var _b = strType.split('^'), typeNames = _b[0], superName = _b[1];
typeNames.split(',').forEach(function (tag) { return _this._schema[tag.toLowerCase()] = type; });
var superType = superName && _this._schema[superName.toLowerCase()];
if (superType) {
Object.keys(superType).forEach(function (prop) { type[prop] = superType[prop]; });
}
properties.forEach(function (property) {
if (property.length > 0) {
switch (property[0]) {
case '*':
// We don't yet support events.
// If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events
// will
// almost certainly introduce bad XSS vulnerabilities.
// type[property.substring(1)] = EVENT;
break;
case '!':
type[property.substring(1)] = BOOLEAN;
break;
case '#':
type[property.substring(1)] = NUMBER;
break;
case '%':
type[property.substring(1)] = OBJECT;
break;
default:
type[property] = STRING;
}
}
});
});
return _this;
}
/**
* @param {?} tagName
* @param {?} propName
* @param {?} schemaMetas
* @return {?}
*/
DomElementSchemaRegistry.prototype.hasProperty = function (tagName, propName, schemaMetas) {
if (schemaMetas.some(function (schema) { return schema.name === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_56" /* NO_ERRORS_SCHEMA */].name; })) {
return true;
}
if (tagName.indexOf('-') > -1) {
if (isNgContainer(tagName) || isNgContent(tagName)) {
return false;
}
if (schemaMetas.some(function (schema) { return schema.name === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_57" /* CUSTOM_ELEMENTS_SCHEMA */].name; })) {
// Can't tell now as we don't know which properties a custom element will get
// once it is instantiated
return true;
}
}
var /** @type {?} */ elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
return !!elementProperties[propName];
};
/**
* @param {?} tagName
* @param {?} schemaMetas
* @return {?}
*/
DomElementSchemaRegistry.prototype.hasElement = function (tagName, schemaMetas) {
if (schemaMetas.some(function (schema) { return schema.name === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_56" /* NO_ERRORS_SCHEMA */].name; })) {
return true;
}
if (tagName.indexOf('-') > -1) {
if (isNgContainer(tagName) || isNgContent(tagName)) {
return true;
}
if (schemaMetas.some(function (schema) { return schema.name === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_57" /* CUSTOM_ELEMENTS_SCHEMA */].name; })) {
// Allow any custom elements
return true;
}
}
return !!this._schema[tagName.toLowerCase()];
};
/**
* securityContext returns the security context for the given property on the given DOM tag.
*
* Tag and property name are statically known and cannot change at runtime, i.e. it is not
* possible to bind a value into a changing attribute or tag name.
*
* The filtering is white list based. All attributes in the schema above are assumed to have the
* 'NONE' security context, i.e. that they are safe inert string values. Only specific well known
* attack vectors are assigned their appropriate context.
* @param {?} tagName
* @param {?} propName
* @param {?} isAttribute
* @return {?}
*/
DomElementSchemaRegistry.prototype.securityContext = function (tagName, propName, isAttribute) {
if (isAttribute) {
// NB: For security purposes, use the mapped property name, not the attribute name.
propName = this.getMappedPropName(propName);
}
// Make sure comparisons are case insensitive, so that case differences between attribute and
// property names do not have a security impact.
tagName = tagName.toLowerCase();
propName = propName.toLowerCase();
var /** @type {?} */ ctx = SECURITY_SCHEMA[tagName + '|' + propName];
if (ctx) {
return ctx;
}
ctx = SECURITY_SCHEMA['*|' + propName];
return ctx ? ctx : __WEBPACK_IMPORTED_MODULE_0__angular_core__["F" /* SecurityContext */].NONE;
};
/**
* @param {?} propName
* @return {?}
*/
DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) { return _ATTR_TO_PROP[propName] || propName; };
/**
* @return {?}
*/
DomElementSchemaRegistry.prototype.getDefaultComponentElementName = function () { return 'ng-component'; };
/**
* @param {?} name
* @return {?}
*/
DomElementSchemaRegistry.prototype.validateProperty = function (name) {
if (name.toLowerCase().startsWith('on')) {
var /** @type {?} */ msg = "Binding to event property '" + name + "' is disallowed for security reasons, " +
("please use (" + name.slice(2) + ")=...") +
("\nIf '" + name + "' is a directive input, make sure the directive is imported by the") +
" current module.";
return { error: true, msg: msg };
}
else {
return { error: false };
}
};
/**
* @param {?} name
* @return {?}
*/
DomElementSchemaRegistry.prototype.validateAttribute = function (name) {
if (name.toLowerCase().startsWith('on')) {
var /** @type {?} */ msg = "Binding to event attribute '" + name + "' is disallowed for security reasons, " +
("please use (" + name.slice(2) + ")=...");
return { error: true, msg: msg };
}
else {
return { error: false };
}
};
/**
* @return {?}
*/
DomElementSchemaRegistry.prototype.allKnownElementNames = function () { return Object.keys(this._schema); };
/**
* @param {?} propName
* @return {?}
*/
DomElementSchemaRegistry.prototype.normalizeAnimationStyleProperty = function (propName) {
return dashCaseToCamelCase(propName);
};
/**
* @param {?} camelCaseProp
* @param {?} userProvidedProp
* @param {?} val
* @return {?}
*/
DomElementSchemaRegistry.prototype.normalizeAnimationStyleValue = function (camelCaseProp, userProvidedProp, val) {
var /** @type {?} */ unit = '';
var /** @type {?} */ strVal = val.toString().trim();
var /** @type {?} */ errorMsg = ((null));
if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
if (typeof val === 'number') {
unit = 'px';
}
else {
var /** @type {?} */ valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
errorMsg = "Please provide a CSS unit value for " + userProvidedProp + ":" + val;
}
}
}
return { error: errorMsg, value: strVal + unit };
};
return DomElementSchemaRegistry;
}(ElementSchemaRegistry));
DomElementSchemaRegistry.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
DomElementSchemaRegistry.ctorParameters = function () { return []; };
/**
* @param {?} prop
* @return {?}
*/
function _isPixelDimensionStyle(prop) {
switch (prop) {
case 'width':
case 'height':
case 'minWidth':
case 'minHeight':
case 'maxWidth':
case 'maxHeight':
case 'left':
case 'top':
case 'bottom':
case 'right':
case 'fontSize':
case 'outlineWidth':
case 'outlineOffset':
case 'paddingTop':
case 'paddingLeft':
case 'paddingBottom':
case 'paddingRight':
case 'marginTop':
case 'marginLeft':
case 'marginBottom':
case 'marginRight':
case 'borderRadius':
case 'borderWidth':
case 'borderTopWidth':
case 'borderLeftWidth':
case 'borderRightWidth':
case 'borderBottomWidth':
case 'textIndent':
return true;
default:
return false;
}
}
var ShadowCss = (function () {
function ShadowCss() {
this.strictStyling = true;
}
/**
* @param {?} cssText
* @param {?} selector
* @param {?=} hostSelector
* @return {?}
*/
ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) {
if (hostSelector === void 0) { hostSelector = ''; }
var /** @type {?} */ sourceMappingUrl = extractSourceMappingUrl(cssText);
cssText = stripComments(cssText);
cssText = this._insertDirectives(cssText);
return this._scopeCssText(cssText, selector, hostSelector) + sourceMappingUrl;
};
/**
* @param {?} cssText
* @return {?}
*/
ShadowCss.prototype._insertDirectives = function (cssText) {
cssText = this._insertPolyfillDirectivesInCssText(cssText);
return this._insertPolyfillRulesInCssText(cssText);
};
/**
* @param {?} cssText
* @return {?}
*/
ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) {
// Difference with webcomponents.js: does not handle comments
return cssText.replace(_cssContentNextSelectorRe, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
return m[2] + '{';
});
};
/**
* @param {?} cssText
* @return {?}
*/
ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) {
// Difference with webcomponents.js: does not handle comments
return cssText.replace(_cssContentRuleRe, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
var /** @type {?} */ rule = m[0].replace(m[1], '').replace(m[2], '');
return m[4] + rule;
});
};
/**
* @param {?} cssText
* @param {?} scopeSelector
* @param {?} hostSelector
* @return {?}
*/
ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) {
var /** @type {?} */ unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
// replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
cssText = this._insertPolyfillHostInCssText(cssText);
cssText = this._convertColonHost(cssText);
cssText = this._convertColonHostContext(cssText);
cssText = this._convertShadowDOMSelectors(cssText);
if (scopeSelector) {
cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
}
cssText = cssText + '\n' + unscopedRules;
return cssText.trim();
};
/**
* @param {?} cssText
* @return {?}
*/
ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) {
// Difference with webcomponents.js: does not handle comments
var /** @type {?} */ r = '';
var /** @type {?} */ m;
_cssContentUnscopedRuleRe.lastIndex = 0;
while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
var /** @type {?} */ rule = m[0].replace(m[2], '').replace(m[1], m[4]);
r += rule + '\n\n';
}
return r;
};
/**
* @param {?} cssText
* @return {?}
*/
ShadowCss.prototype._convertColonHost = function (cssText) {
return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
};
/**
* @param {?} cssText
* @return {?}
*/
ShadowCss.prototype._convertColonHostContext = function (cssText) {
return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
};
/**
* @param {?} cssText
* @param {?} regExp
* @param {?} partReplacer
* @return {?}
*/
ShadowCss.prototype._convertColonRule = function (cssText, regExp, partReplacer) {
// m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule
return cssText.replace(regExp, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
if (m[2]) {
var /** @type {?} */ parts = m[2].split(',');
var /** @type {?} */ r = [];
for (var /** @type {?} */ i = 0; i < parts.length; i++) {
var /** @type {?} */ p = parts[i].trim();
if (!p)
break;
r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
}
return r.join(',');
}
else {
return _polyfillHostNoCombinator + m[3];
}
});
};
/**
* @param {?} host
* @param {?} part
* @param {?} suffix
* @return {?}
*/
ShadowCss.prototype._colonHostContextPartReplacer = function (host, part, suffix) {
if (part.indexOf(_polyfillHost) > -1) {
return this._colonHostPartReplacer(host, part, suffix);
}
else {
return host + part + suffix + ', ' + part + ' ' + host + suffix;
}
};
/**
* @param {?} host
* @param {?} part
* @param {?} suffix
* @return {?}
*/
ShadowCss.prototype._colonHostPartReplacer = function (host, part, suffix) {
return host + part.replace(_polyfillHost, '') + suffix;
};
/**
* @param {?} cssText
* @return {?}
*/
ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) {
return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText);
};
/**
* @param {?} cssText
* @param {?} scopeSelector
* @param {?} hostSelector
* @return {?}
*/
ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) {
var _this = this;
return processRules(cssText, function (rule) {
var /** @type {?} */ selector = rule.selector;
var /** @type {?} */ content = rule.content;
if (rule.selector[0] != '@') {
selector =
_this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling);
}
else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector);
}
return new CssRule(selector, content);
});
};
/**
* @param {?} selector
* @param {?} scopeSelector
* @param {?} hostSelector
* @param {?} strict
* @return {?}
*/
ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) {
var _this = this;
return selector.split(',')
.map(function (part) { return part.trim().split(_shadowDeepSelectors); })
.map(function (deepParts) {
var shallowPart = deepParts[0], otherParts = deepParts.slice(1);
var /** @type {?} */ applyScope = function (shallowPart) {
if (_this._selectorNeedsScoping(shallowPart, scopeSelector)) {
return strict ?
_this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
_this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
}
else {
return shallowPart;
}
};
return [applyScope(shallowPart)].concat(otherParts).join(' ');
})
.join(', ');
};
/**
* @param {?} selector
* @param {?} scopeSelector
* @return {?}
*/
ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) {
var /** @type {?} */ re = this._makeScopeMatcher(scopeSelector);
return !re.test(selector);
};
/**
* @param {?} scopeSelector
* @return {?}
*/
ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) {
var /** @type {?} */ lre = /\[/g;
var /** @type {?} */ rre = /\]/g;
scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
};
/**
* @param {?} selector
* @param {?} scopeSelector
* @param {?} hostSelector
* @return {?}
*/
ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) {
// Difference from webcomponents.js: scopeSelector could not be an array
return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
};
/**
* @param {?} selector
* @param {?} scopeSelector
* @param {?} hostSelector
* @return {?}
*/
ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) {
// In Android browser, the lastIndex is not reset when the regex is used in String.replace()
_polyfillHostRe.lastIndex = 0;
if (_polyfillHostRe.test(selector)) {
var /** @type {?} */ replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector;
return selector
.replace(_polyfillHostNoCombinatorRe, function (hnc, selector) {
return selector.replace(/([^:]*)(:*)(.*)/, function (_, before, colon, after) {
return before + replaceBy_1 + colon + after;
});
})
.replace(_polyfillHostRe, replaceBy_1 + ' ');
}
return scopeSelector + ' ' + selector;
};
/**
* @param {?} selector
* @param {?} scopeSelector
* @param {?} hostSelector
* @return {?}
*/
ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector, hostSelector) {
var _this = this;
var /** @type {?} */ isRe = /\[is=([^\]]*)\]/g;
scopeSelector = scopeSelector.replace(isRe, function (_) {
var parts = [];
for (var _i = 1; _i < arguments.length; _i++) {
parts[_i - 1] = arguments[_i];
}
return parts[0];
});
var /** @type {?} */ attrName = '[' + scopeSelector + ']';
var /** @type {?} */ _scopeSelectorPart = function (p) {
var /** @type {?} */ scopedP = p.trim();
if (!scopedP) {
return '';
}
if (p.indexOf(_polyfillHostNoCombinator) > -1) {
scopedP = _this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
}
else {
// remove :host since it should be unnecessary
var /** @type {?} */ t = p.replace(_polyfillHostRe, '');
if (t.length > 0) {
var /** @type {?} */ matches = t.match(/([^:]*)(:*)(.*)/);
if (matches) {
scopedP = matches[1] + attrName + matches[2] + matches[3];
}
}
}
return scopedP;
};
var /** @type {?} */ safeContent = new SafeSelector(selector);
selector = safeContent.content();
var /** @type {?} */ scopedSelector = '';
var /** @type {?} */ startIndex = 0;
var /** @type {?} */ res;
var /** @type {?} */ sep = /( |>|\+|~(?!=))\s*/g;
var /** @type {?} */ scopeAfter = selector.indexOf(_polyfillHostNoCombinator);
while ((res = sep.exec(selector)) !== null) {
var /** @type {?} */ separator = res[1];
var /** @type {?} */ part = selector.slice(startIndex, res.index).trim();
// if a selector appears before :host-context it should not be shimmed as it
// matches on ancestor elements and not on elements in the host's shadow
var /** @type {?} */ scopedPart = startIndex >= scopeAfter ? _scopeSelectorPart(part) : part;
scopedSelector += scopedPart + " " + separator + " ";
startIndex = sep.lastIndex;
}
scopedSelector += _scopeSelectorPart(selector.substring(startIndex));
// replace the placeholders with their original values
return safeContent.restore(scopedSelector);
};
/**
* @param {?} selector
* @return {?}
*/
ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) {
return selector.replace(_colonHostContextRe, _polyfillHostContext)
.replace(_colonHostRe, _polyfillHost);
};
return ShadowCss;
}());
var SafeSelector = (function () {
/**
* @param {?} selector
*/
function SafeSelector(selector) {
var _this = this;
this.placeholders = [];
this.index = 0;
// Replaces attribute selectors with placeholders.
// The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
selector = selector.replace(/(\[[^\]]*\])/g, function (_, keep) {
var replaceBy = "__ph-" + _this.index + "__";
_this.placeholders.push(keep);
_this.index++;
return replaceBy;
});
// Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
// WS and "+" would otherwise be interpreted as selector separators.
this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, function (_, pseudo, exp) {
var replaceBy = "__ph-" + _this.index + "__";
_this.placeholders.push(exp);
_this.index++;
return pseudo + replaceBy;
});
}
;
/**
* @param {?} content
* @return {?}
*/
SafeSelector.prototype.restore = function (content) {
var _this = this;
return content.replace(/__ph-(\d+)__/g, function (ph, index) { return _this.placeholders[+index]; });
};
/**
* @return {?}
*/
SafeSelector.prototype.content = function () { return this._content; };
return SafeSelector;
}());
var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
var _polyfillHost = '-shadowcsshost';
// note: :host-context pre-processed to -shadowcsshostcontext.
var _polyfillHostContext = '-shadowcsscontext';
var _parenSuffix = ')(?:\\((' +
'(?:\\([^)(]*\\)|[^)(]*)+?' +
')\\))?([^,{]*)';
var _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
var _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
var _shadowDOMSelectorsRe = [
/::shadow/g,
/::content/g,
// Deprecated selectors
/\/shadow-deep\//g,
/\/shadow\//g,
];
var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)/g;
var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
var _polyfillHostRe = /-shadowcsshost/gim;
var _colonHostRe = /:host/gim;
var _colonHostContextRe = /:host-context/gim;
var _commentRe = /\/\*\s*[\s\S]*?\*\//g;
/**
* @param {?} input
* @return {?}
*/
function stripComments(input) {
return input.replace(_commentRe, '');
}
// all comments except inline source mapping
var _sourceMappingUrlRe = /\/\*\s*#\s*sourceMappingURL=[\s\S]+?\*\//;
/**
* @param {?} input
* @return {?}
*/
function extractSourceMappingUrl(input) {
var /** @type {?} */ matcher = input.match(_sourceMappingUrlRe);
return matcher ? matcher[0] : '';
}
var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
var _curlyRe = /([{}])/g;
var OPEN_CURLY = '{';
var CLOSE_CURLY = '}';
var BLOCK_PLACEHOLDER = '%BLOCK%';
var CssRule = (function () {
/**
* @param {?} selector
* @param {?} content
*/
function CssRule(selector, content) {
this.selector = selector;
this.content = content;
}
return CssRule;
}());
/**
* @param {?} input
* @param {?} ruleCallback
* @return {?}
*/
function processRules(input, ruleCallback) {
var /** @type {?} */ inputWithEscapedBlocks = escapeBlocks(input);
var /** @type {?} */ nextBlockIndex = 0;
return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
var /** @type {?} */ selector = m[2];
var /** @type {?} */ content = '';
var /** @type {?} */ suffix = m[4];
var /** @type {?} */ contentPrefix = '';
if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
contentPrefix = '{';
}
var /** @type {?} */ rule = ruleCallback(new CssRule(selector, content));
return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix;
});
}
var StringWithEscapedBlocks = (function () {
/**
* @param {?} escapedString
* @param {?} blocks
*/
function StringWithEscapedBlocks(escapedString, blocks) {
this.escapedString = escapedString;
this.blocks = blocks;
}
return StringWithEscapedBlocks;
}());
/**
* @param {?} input
* @return {?}
*/
function escapeBlocks(input) {
var /** @type {?} */ inputParts = input.split(_curlyRe);
var /** @type {?} */ resultParts = [];
var /** @type {?} */ escapedBlocks = [];
var /** @type {?} */ bracketCount = 0;
var /** @type {?} */ currentBlockParts = [];
for (var /** @type {?} */ partIndex = 0; partIndex < inputParts.length; partIndex++) {
var /** @type {?} */ part = inputParts[partIndex];
if (part == CLOSE_CURLY) {
bracketCount--;
}
if (bracketCount > 0) {
currentBlockParts.push(part);
}
else {
if (currentBlockParts.length > 0) {
escapedBlocks.push(currentBlockParts.join(''));
resultParts.push(BLOCK_PLACEHOLDER);
currentBlockParts = [];
}
resultParts.push(part);
}
if (part == OPEN_CURLY) {
bracketCount++;
}
}
if (currentBlockParts.length > 0) {
escapedBlocks.push(currentBlockParts.join(''));
resultParts.push(BLOCK_PLACEHOLDER);
}
return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
}
/**
* @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
*/
var COMPONENT_VARIABLE = '%COMP%';
var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE;
var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE;
var StylesCompileDependency = (function () {
/**
* @param {?} name
* @param {?} moduleUrl
* @param {?} isShimmed
* @param {?} valuePlaceholder
*/
function StylesCompileDependency(name, moduleUrl, isShimmed, valuePlaceholder) {
this.name = name;
this.moduleUrl = moduleUrl;
this.isShimmed = isShimmed;
this.valuePlaceholder = valuePlaceholder;
}
return StylesCompileDependency;
}());
var StylesCompileResult = (function () {
/**
* @param {?} componentStylesheet
* @param {?} externalStylesheets
*/
function StylesCompileResult(componentStylesheet, externalStylesheets) {
this.componentStylesheet = componentStylesheet;
this.externalStylesheets = externalStylesheets;
}
return StylesCompileResult;
}());
var CompiledStylesheet = (function () {
/**
* @param {?} statements
* @param {?} stylesVar
* @param {?} dependencies
* @param {?} isShimmed
* @param {?} meta
*/
function CompiledStylesheet(statements, stylesVar, dependencies, isShimmed, meta) {
this.statements = statements;
this.stylesVar = stylesVar;
this.dependencies = dependencies;
this.isShimmed = isShimmed;
this.meta = meta;
}
return CompiledStylesheet;
}());
var StyleCompiler = (function () {
/**
* @param {?} _urlResolver
*/
function StyleCompiler(_urlResolver) {
this._urlResolver = _urlResolver;
this._shadowCss = new ShadowCss();
}
/**
* @param {?} comp
* @return {?}
*/
StyleCompiler.prototype.compileComponent = function (comp) {
var _this = this;
var /** @type {?} */ template = ((comp.template));
var /** @type {?} */ externalStylesheets = [];
var /** @type {?} */ componentStylesheet = this._compileStyles(comp, new CompileStylesheetMetadata({
styles: template.styles,
styleUrls: template.styleUrls,
moduleUrl: identifierModuleUrl(comp.type)
}), true);
template.externalStylesheets.forEach(function (stylesheetMeta) {
var /** @type {?} */ compiledStylesheet = _this._compileStyles(comp, stylesheetMeta, false);
externalStylesheets.push(compiledStylesheet);
});
return new StylesCompileResult(componentStylesheet, externalStylesheets);
};
/**
* @param {?} comp
* @param {?} stylesheet
* @param {?} isComponentStylesheet
* @return {?}
*/
StyleCompiler.prototype._compileStyles = function (comp, stylesheet, isComponentStylesheet) {
var _this = this;
var /** @type {?} */ shim = ((comp.template)).encapsulation === __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].Emulated;
var /** @type {?} */ styleExpressions = stylesheet.styles.map(function (plainStyle) { return literal(_this._shimIfNeeded(plainStyle, shim)); });
var /** @type {?} */ dependencies = [];
for (var /** @type {?} */ i = 0; i < stylesheet.styleUrls.length; i++) {
var /** @type {?} */ identifier = { reference: null };
dependencies.push(new StylesCompileDependency(getStylesVarName(null), stylesheet.styleUrls[i], shim, identifier));
styleExpressions.push(new ExternalExpr(identifier));
}
// styles variable contains plain strings and arrays of other styles arrays (recursive),
// so we set its type to dynamic.
var /** @type {?} */ stylesVar = getStylesVarName(isComponentStylesheet ? comp : null);
var /** @type {?} */ stmt = variable(stylesVar)
.set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const])))
.toDeclStmt(null, [StmtModifier.Final]);
return new CompiledStylesheet([stmt], stylesVar, dependencies, shim, stylesheet);
};
/**
* @param {?} style
* @param {?} shim
* @return {?}
*/
StyleCompiler.prototype._shimIfNeeded = function (style$$1, shim) {
return shim ? this._shadowCss.shimCssText(style$$1, CONTENT_ATTR, HOST_ATTR) : style$$1;
};
return StyleCompiler;
}());
StyleCompiler.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
StyleCompiler.ctorParameters = function () { return [
{ type: UrlResolver, },
]; };
/**
* @param {?} component
* @return {?}
*/
function getStylesVarName(component) {
var /** @type {?} */ result = "styles";
if (component) {
result += "_" + identifierName(component.type);
}
return result;
}
/**
* @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
*/
var EventHandlerVars = (function () {
function EventHandlerVars() {
}
return EventHandlerVars;
}());
EventHandlerVars.event = variable('$event');
var ConvertActionBindingResult = (function () {
/**
* @param {?} stmts
* @param {?} allowDefault
*/
function ConvertActionBindingResult(stmts, allowDefault) {
this.stmts = stmts;
this.allowDefault = allowDefault;
}
return ConvertActionBindingResult;
}());
/**
* Converts the given expression AST into an executable output AST, assuming the expression is
* used in an action binding (e.g. an event handler).
* @param {?} localResolver
* @param {?} implicitReceiver
* @param {?} action
* @param {?} bindingId
* @return {?}
*/
function convertActionBinding(localResolver, implicitReceiver, action, bindingId) {
if (!localResolver) {
localResolver = new DefaultLocalResolver();
}
var /** @type {?} */ actionWithoutBuiltins = convertPropertyBindingBuiltins({
createLiteralArrayConverter: function (argCount) {
// Note: no caching for literal arrays in actions.
return function (args) { return literalArr(args); };
},
createLiteralMapConverter: function (keys) {
// Note: no caching for literal maps in actions.
return function (args) { return literalMap(/** @type {?} */ (keys.map(function (key, i) { return [key, args[i]]; }))); };
},
createPipeConverter: function (name) {
throw new Error("Illegal State: Actions are not allowed to contain pipes. Pipe: " + name);
}
}, action);
var /** @type {?} */ visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId);
var /** @type {?} */ actionStmts = [];
flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts);
prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
var /** @type {?} */ lastIndex = actionStmts.length - 1;
var /** @type {?} */ preventDefaultVar = ((null));
if (lastIndex >= 0) {
var /** @type {?} */ lastStatement = actionStmts[lastIndex];
var /** @type {?} */ returnExpr = convertStmtIntoExpression(lastStatement);
if (returnExpr) {
// Note: We need to cast the result of the method call to dynamic,
// as it might be a void method!
preventDefaultVar = createPreventDefaultVar(bindingId);
actionStmts[lastIndex] =
preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false)))
.toDeclStmt(null, [StmtModifier.Final]);
}
}
return new ConvertActionBindingResult(actionStmts, preventDefaultVar);
}
/**
* @param {?} converterFactory
* @param {?} ast
* @return {?}
*/
function convertPropertyBindingBuiltins(converterFactory, ast) {
return convertBuiltins(converterFactory, ast);
}
var ConvertPropertyBindingResult = (function () {
/**
* @param {?} stmts
* @param {?} currValExpr
*/
function ConvertPropertyBindingResult(stmts, currValExpr) {
this.stmts = stmts;
this.currValExpr = currValExpr;
}
return ConvertPropertyBindingResult;
}());
/**
* Converts the given expression AST into an executable output AST, assuming the expression
* is used in property binding. The expression has to be preprocessed via
* `convertPropertyBindingBuiltins`.
* @param {?} localResolver
* @param {?} implicitReceiver
* @param {?} expressionWithoutBuiltins
* @param {?} bindingId
* @return {?}
*/
function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId) {
if (!localResolver) {
localResolver = new DefaultLocalResolver();
}
var /** @type {?} */ currValExpr = createCurrValueExpr(bindingId);
var /** @type {?} */ stmts = [];
var /** @type {?} */ visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId);
var /** @type {?} */ outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression);
if (visitor.temporaryCount) {
for (var /** @type {?} */ i = 0; i < visitor.temporaryCount; i++) {
stmts.push(temporaryDeclaration(bindingId, i));
}
}
stmts.push(currValExpr.set(outputExpr).toDeclStmt(null, [StmtModifier.Final]));
return new ConvertPropertyBindingResult(stmts, currValExpr);
}
/**
* @param {?} converterFactory
* @param {?} ast
* @return {?}
*/
function convertBuiltins(converterFactory, ast) {
var /** @type {?} */ visitor = new _BuiltinAstConverter(converterFactory);
return ast.visit(visitor);
}
/**
* @param {?} bindingId
* @param {?} temporaryNumber
* @return {?}
*/
function temporaryName(bindingId, temporaryNumber) {
return "tmp_" + bindingId + "_" + temporaryNumber;
}
/**
* @param {?} bindingId
* @param {?} temporaryNumber
* @return {?}
*/
function temporaryDeclaration(bindingId, temporaryNumber) {
return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber), NULL_EXPR);
}
/**
* @param {?} temporaryCount
* @param {?} bindingId
* @param {?} statements
* @return {?}
*/
function prependTemporaryDecls(temporaryCount, bindingId, statements) {
for (var /** @type {?} */ i = temporaryCount - 1; i >= 0; i--) {
statements.unshift(temporaryDeclaration(bindingId, i));
}
}
var _Mode = {};
_Mode.Statement = 0;
_Mode.Expression = 1;
_Mode[_Mode.Statement] = "Statement";
_Mode[_Mode.Expression] = "Expression";
/**
* @param {?} mode
* @param {?} ast
* @return {?}
*/
function ensureStatementMode(mode, ast) {
if (mode !== _Mode.Statement) {
throw new Error("Expected a statement, but saw " + ast);
}
}
/**
* @param {?} mode
* @param {?} ast
* @return {?}
*/
function ensureExpressionMode(mode, ast) {
if (mode !== _Mode.Expression) {
throw new Error("Expected an expression, but saw " + ast);
}
}
/**
* @param {?} mode
* @param {?} expr
* @return {?}
*/
function convertToStatementIfNeeded(mode, expr) {
if (mode === _Mode.Statement) {
return expr.toStmt();
}
else {
return expr;
}
}
var _BuiltinAstConverter = (function (_super) {
__extends(_BuiltinAstConverter, _super);
/**
* @param {?} _converterFactory
*/
function _BuiltinAstConverter(_converterFactory) {
var _this = _super.call(this) || this;
_this._converterFactory = _converterFactory;
return _this;
}
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
_BuiltinAstConverter.prototype.visitPipe = function (ast, context) {
var _this = this;
var /** @type {?} */ args = [ast.exp].concat(ast.args).map(function (ast) { return ast.visit(_this, context); });
return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createPipeConverter(ast.name, args.length));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
_BuiltinAstConverter.prototype.visitLiteralArray = function (ast, context) {
var _this = this;
var /** @type {?} */ args = ast.expressions.map(function (ast) { return ast.visit(_this, context); });
return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length));
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
_BuiltinAstConverter.prototype.visitLiteralMap = function (ast, context) {
var _this = this;
var /** @type {?} */ args = ast.values.map(function (ast) { return ast.visit(_this, context); });
return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralMapConverter(ast.keys));
};
return _BuiltinAstConverter;
}(AstTransformer));
var _AstToIrVisitor = (function () {
/**
* @param {?} _localResolver
* @param {?} _implicitReceiver
* @param {?} bindingId
*/
function _AstToIrVisitor(_localResolver, _implicitReceiver, bindingId) {
this._localResolver = _localResolver;
this._implicitReceiver = _implicitReceiver;
this.bindingId = bindingId;
this._nodeMap = new Map();
this._resultMap = new Map();
this._currentTemporary = 0;
this.temporaryCount = 0;
}
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitBinary = function (ast, mode) {
var /** @type {?} */ op;
switch (ast.operation) {
case '+':
op = BinaryOperator.Plus;
break;
case '-':
op = BinaryOperator.Minus;
break;
case '*':
op = BinaryOperator.Multiply;
break;
case '/':
op = BinaryOperator.Divide;
break;
case '%':
op = BinaryOperator.Modulo;
break;
case '&&':
op = BinaryOperator.And;
break;
case '||':
op = BinaryOperator.Or;
break;
case '==':
op = BinaryOperator.Equals;
break;
case '!=':
op = BinaryOperator.NotEquals;
break;
case '===':
op = BinaryOperator.Identical;
break;
case '!==':
op = BinaryOperator.NotIdentical;
break;
case '<':
op = BinaryOperator.Lower;
break;
case '>':
op = BinaryOperator.Bigger;
break;
case '<=':
op = BinaryOperator.LowerEquals;
break;
case '>=':
op = BinaryOperator.BiggerEquals;
break;
default:
throw new Error("Unsupported operation " + ast.operation);
}
return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this.visit(ast.left, _Mode.Expression), this.visit(ast.right, _Mode.Expression)));
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitChain = function (ast, mode) {
ensureStatementMode(mode, ast);
return this.visitAll(ast.expressions, mode);
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitConditional = function (ast, mode) {
var /** @type {?} */ value = this.visit(ast.condition, _Mode.Expression);
return convertToStatementIfNeeded(mode, value.conditional(this.visit(ast.trueExp, _Mode.Expression), this.visit(ast.falseExp, _Mode.Expression)));
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitPipe = function (ast, mode) {
throw new Error("Illegal state: Pipes should have been converted into functions. Pipe: " + ast.name);
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitFunctionCall = function (ast, mode) {
var /** @type {?} */ convertedArgs = this.visitAll(ast.args, _Mode.Expression);
var /** @type {?} */ fnResult;
if (ast instanceof BuiltinFunctionCall) {
fnResult = ast.converter(convertedArgs);
}
else {
fnResult = this.visit(/** @type {?} */ ((ast.target)), _Mode.Expression).callFn(convertedArgs);
}
return convertToStatementIfNeeded(mode, fnResult);
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitImplicitReceiver = function (ast, mode) {
ensureExpressionMode(mode, ast);
return this._implicitReceiver;
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitInterpolation = function (ast, mode) {
ensureExpressionMode(mode, ast);
var /** @type {?} */ args = [literal(ast.expressions.length)];
for (var /** @type {?} */ i = 0; i < ast.strings.length - 1; i++) {
args.push(literal(ast.strings[i]));
args.push(this.visit(ast.expressions[i], _Mode.Expression));
}
args.push(literal(ast.strings[ast.strings.length - 1]));
return ast.expressions.length <= 9 ?
importExpr(createIdentifier(Identifiers.inlineInterpolate)).callFn(args) :
importExpr(createIdentifier(Identifiers.interpolate)).callFn([
args[0], literalArr(args.slice(1))
]);
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitKeyedRead = function (ast, mode) {
var /** @type {?} */ leftMostSafe = this.leftMostSafeNode(ast);
if (leftMostSafe) {
return this.convertSafeAccess(ast, leftMostSafe, mode);
}
else {
return convertToStatementIfNeeded(mode, this.visit(ast.obj, _Mode.Expression).key(this.visit(ast.key, _Mode.Expression)));
}
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitKeyedWrite = function (ast, mode) {
var /** @type {?} */ obj = this.visit(ast.obj, _Mode.Expression);
var /** @type {?} */ key = this.visit(ast.key, _Mode.Expression);
var /** @type {?} */ value = this.visit(ast.value, _Mode.Expression);
return convertToStatementIfNeeded(mode, obj.key(key).set(value));
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitLiteralArray = function (ast, mode) {
throw new Error("Illegal State: literal arrays should have been converted into functions");
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitLiteralMap = function (ast, mode) {
throw new Error("Illegal State: literal maps should have been converted into functions");
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitLiteralPrimitive = function (ast, mode) {
return convertToStatementIfNeeded(mode, literal(ast.value));
};
/**
* @param {?} name
* @return {?}
*/
_AstToIrVisitor.prototype._getLocal = function (name) { return this._localResolver.getLocal(name); };
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitMethodCall = function (ast, mode) {
var /** @type {?} */ leftMostSafe = this.leftMostSafeNode(ast);
if (leftMostSafe) {
return this.convertSafeAccess(ast, leftMostSafe, mode);
}
else {
var /** @type {?} */ args = this.visitAll(ast.args, _Mode.Expression);
var /** @type {?} */ result = null;
var /** @type {?} */ receiver = this.visit(ast.receiver, _Mode.Expression);
if (receiver === this._implicitReceiver) {
var /** @type {?} */ varExpr = this._getLocal(ast.name);
if (varExpr) {
result = varExpr.callFn(args);
}
}
if (result == null) {
result = receiver.callMethod(ast.name, args);
}
return convertToStatementIfNeeded(mode, result);
}
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitPrefixNot = function (ast, mode) {
return convertToStatementIfNeeded(mode, not(this.visit(ast.expression, _Mode.Expression)));
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitPropertyRead = function (ast, mode) {
var /** @type {?} */ leftMostSafe = this.leftMostSafeNode(ast);
if (leftMostSafe) {
return this.convertSafeAccess(ast, leftMostSafe, mode);
}
else {
var /** @type {?} */ result = null;
var /** @type {?} */ receiver = this.visit(ast.receiver, _Mode.Expression);
if (receiver === this._implicitReceiver) {
result = this._getLocal(ast.name);
}
if (result == null) {
result = receiver.prop(ast.name);
}
return convertToStatementIfNeeded(mode, result);
}
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitPropertyWrite = function (ast, mode) {
var /** @type {?} */ receiver = this.visit(ast.receiver, _Mode.Expression);
if (receiver === this._implicitReceiver) {
var /** @type {?} */ varExpr = this._getLocal(ast.name);
if (varExpr) {
throw new Error('Cannot assign to a reference or variable!');
}
}
return convertToStatementIfNeeded(mode, receiver.prop(ast.name).set(this.visit(ast.value, _Mode.Expression)));
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitSafePropertyRead = function (ast, mode) {
return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitSafeMethodCall = function (ast, mode) {
return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
};
/**
* @param {?} asts
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitAll = function (asts, mode) {
var _this = this;
return asts.map(function (ast) { return _this.visit(ast, mode); });
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visitQuote = function (ast, mode) {
throw new Error("Quotes are not supported for evaluation!\n Statement: " + ast.uninterpretedExpression + " located at " + ast.location);
};
/**
* @param {?} ast
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.visit = function (ast, mode) {
var /** @type {?} */ result = this._resultMap.get(ast);
if (result)
return result;
return (this._nodeMap.get(ast) || ast).visit(this, mode);
};
/**
* @param {?} ast
* @param {?} leftMostSafe
* @param {?} mode
* @return {?}
*/
_AstToIrVisitor.prototype.convertSafeAccess = function (ast, leftMostSafe, mode) {
// If the expression contains a safe access node on the left it needs to be converted to
// an expression that guards the access to the member by checking the receiver for blank. As
// execution proceeds from left to right, the left most part of the expression must be guarded
// first but, because member access is left associative, the right side of the expression is at
// the top of the AST. The desired result requires lifting a copy of the the left part of the
// expression up to test it for blank before generating the unguarded version.
// Consider, for example the following expression: a?.b.c?.d.e
// This results in the ast:
// .
// / \
// ?. e
// / \
// . d
// / \
// ?. c
// / \
// a b
// The following tree should be generated:
//
// /---- ? ----\
// / | \
// a /--- ? ---\ null
// / | \
// . . null
// / \ / \
// . c . e
// / \ / \
// a b , d
// / \
// . c
// / \
// a b
//
// Notice that the first guard condition is the left hand of the left most safe access node
// which comes in as leftMostSafe to this routine.
var /** @type {?} */ guardedExpression = this.visit(leftMostSafe.receiver, _Mode.Expression);
var /** @type {?} */ temporary = ((undefined));
if (this.needsTemporary(leftMostSafe.receiver)) {
// If the expression has method calls or pipes then we need to save the result into a
// temporary variable to avoid calling stateful or impure code more than once.
temporary = this.allocateTemporary();
// Preserve the result in the temporary variable
guardedExpression = temporary.set(guardedExpression);
// Ensure all further references to the guarded expression refer to the temporary instead.
this._resultMap.set(leftMostSafe.receiver, temporary);
}
var /** @type {?} */ condition = guardedExpression.isBlank();
// Convert the ast to an unguarded access to the receiver's member. The map will substitute
// leftMostNode with its unguarded version in the call to `this.visit()`.
if (leftMostSafe instanceof SafeMethodCall) {
this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args));
}
else {
this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name));
}
// Recursively convert the node now without the guarded member access.
var /** @type {?} */ access = this.visit(ast, _Mode.Expression);
// Remove the mapping. This is not strictly required as the converter only traverses each node
// once but is safer if the conversion is changed to traverse the nodes more than once.
this._nodeMap.delete(leftMostSafe);
// If we allocated a temporary, release it.
if (temporary) {
this.releaseTemporary(temporary);
}
// Produce the conditional
return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access));
};
/**
* @param {?} ast
* @return {?}
*/
_AstToIrVisitor.prototype.leftMostSafeNode = function (ast) {
var _this = this;
var /** @type {?} */ visit = function (visitor, ast) {
return (_this._nodeMap.get(ast) || ast).visit(visitor);
};
return ast.visit({
/**
* @param {?} ast
* @return {?}
*/
visitBinary: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitChain: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitConditional: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitFunctionCall: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitImplicitReceiver: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitInterpolation: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitKeyedRead: function (ast) { return visit(this, ast.obj); },
/**
* @param {?} ast
* @return {?}
*/
visitKeyedWrite: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitLiteralArray: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitLiteralMap: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitLiteralPrimitive: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitMethodCall: function (ast) { return visit(this, ast.receiver); },
/**
* @param {?} ast
* @return {?}
*/
visitPipe: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitPrefixNot: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitPropertyRead: function (ast) { return visit(this, ast.receiver); },
/**
* @param {?} ast
* @return {?}
*/
visitPropertyWrite: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitQuote: function (ast) { return null; },
/**
* @param {?} ast
* @return {?}
*/
visitSafeMethodCall: function (ast) { return visit(this, ast.receiver) || ast; },
/**
* @param {?} ast
* @return {?}
*/
visitSafePropertyRead: function (ast) {
return visit(this, ast.receiver) || ast;
}
});
};
/**
* @param {?} ast
* @return {?}
*/
_AstToIrVisitor.prototype.needsTemporary = function (ast) {
var _this = this;
var /** @type {?} */ visit = function (visitor, ast) {
return ast && (_this._nodeMap.get(ast) || ast).visit(visitor);
};
var /** @type {?} */ visitSome = function (visitor, ast) {
return ast.some(function (ast) { return visit(visitor, ast); });
};
return ast.visit({
/**
* @param {?} ast
* @return {?}
*/
visitBinary: function (ast) { return visit(this, ast.left) || visit(this, ast.right); },
/**
* @param {?} ast
* @return {?}
*/
visitChain: function (ast) { return false; },
/**
* @param {?} ast
* @return {?}
*/
visitConditional: function (ast) {
return visit(this, ast.condition) || visit(this, ast.trueExp) ||
visit(this, ast.falseExp);
},
/**
* @param {?} ast
* @return {?}
*/
visitFunctionCall: function (ast) { return true; },
/**
* @param {?} ast
* @return {?}
*/
visitImplicitReceiver: function (ast) { return false; },
/**
* @param {?} ast
* @return {?}
*/
visitInterpolation: function (ast) { return visitSome(this, ast.expressions); },
/**
* @param {?} ast
* @return {?}
*/
visitKeyedRead: function (ast) { return false; },
/**
* @param {?} ast
* @return {?}
*/
visitKeyedWrite: function (ast) { return false; },
/**
* @param {?} ast
* @return {?}
*/
visitLiteralArray: function (ast) { return true; },
/**
* @param {?} ast
* @return {?}
*/
visitLiteralMap: function (ast) { return true; },
/**
* @param {?} ast
* @return {?}
*/
visitLiteralPrimitive: function (ast) { return false; },
/**
* @param {?} ast
* @return {?}
*/
visitMethodCall: function (ast) { return true; },
/**
* @param {?} ast
* @return {?}
*/
visitPipe: function (ast) { return true; },
/**
* @param {?} ast
* @return {?}
*/
visitPrefixNot: function (ast) { return visit(this, ast.expression); },
/**
* @param {?} ast
* @return {?}
*/
visitPropertyRead: function (ast) { return false; },
/**
* @param {?} ast
* @return {?}
*/
visitPropertyWrite: function (ast) { return false; },
/**
* @param {?} ast
* @return {?}
*/
visitQuote: function (ast) { return false; },
/**
* @param {?} ast
* @return {?}
*/
visitSafeMethodCall: function (ast) { return true; },
/**
* @param {?} ast
* @return {?}
*/
visitSafePropertyRead: function (ast) { return false; }
});
};
/**
* @return {?}
*/
_AstToIrVisitor.prototype.allocateTemporary = function () {
var /** @type {?} */ tempNumber = this._currentTemporary++;
this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount);
return new ReadVarExpr(temporaryName(this.bindingId, tempNumber));
};
/**
* @param {?} temporary
* @return {?}
*/
_AstToIrVisitor.prototype.releaseTemporary = function (temporary) {
this._currentTemporary--;
if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) {
throw new Error("Temporary " + temporary.name + " released out of order");
}
};
return _AstToIrVisitor;
}());
/**
* @param {?} arg
* @param {?} output
* @return {?}
*/
function flattenStatements(arg, output) {
if (Array.isArray(arg)) {
((arg)).forEach(function (entry) { return flattenStatements(entry, output); });
}
else {
output.push(arg);
}
}
var DefaultLocalResolver = (function () {
function DefaultLocalResolver() {
}
/**
* @param {?} name
* @return {?}
*/
DefaultLocalResolver.prototype.getLocal = function (name) {
if (name === EventHandlerVars.event.name) {
return EventHandlerVars.event;
}
return null;
};
return DefaultLocalResolver;
}());
/**
* @param {?} bindingId
* @return {?}
*/
function createCurrValueExpr(bindingId) {
return variable("currVal_" + bindingId); // fix syntax highlighting: `
}
/**
* @param {?} bindingId
* @return {?}
*/
function createPreventDefaultVar(bindingId) {
return variable("pd_" + bindingId);
}
/**
* @param {?} stmt
* @return {?}
*/
function convertStmtIntoExpression(stmt) {
if (stmt instanceof ExpressionStatement) {
return stmt.expr;
}
else if (stmt instanceof ReturnStatement) {
return stmt.value;
}
return null;
}
var BuiltinFunctionCall = (function (_super) {
__extends(BuiltinFunctionCall, _super);
/**
* @param {?} span
* @param {?} args
* @param {?} converter
*/
function BuiltinFunctionCall(span, args, converter) {
var _this = _super.call(this, span, null, args) || this;
_this.args = args;
_this.converter = converter;
return _this;
}
return BuiltinFunctionCall;
}(FunctionCall));
/**
* @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
*/
var CLASS_ATTR$1 = 'class';
var STYLE_ATTR = 'style';
var IMPLICIT_TEMPLATE_VAR = '\$implicit';
var ViewCompileResult = (function () {
/**
* @param {?} statements
* @param {?} viewClassVar
* @param {?} rendererTypeVar
*/
function ViewCompileResult(statements, viewClassVar, rendererTypeVar) {
this.statements = statements;
this.viewClassVar = viewClassVar;
this.rendererTypeVar = rendererTypeVar;
}
return ViewCompileResult;
}());
var ViewCompiler = (function () {
/**
* @param {?} _genConfigNext
* @param {?} _schemaRegistry
*/
function ViewCompiler(_genConfigNext, _schemaRegistry) {
this._genConfigNext = _genConfigNext;
this._schemaRegistry = _schemaRegistry;
}
/**
* @param {?} component
* @param {?} template
* @param {?} styles
* @param {?} usedPipes
* @return {?}
*/
ViewCompiler.prototype.compileComponent = function (component, template, styles, usedPipes) {
var /** @type {?} */ embeddedViewCount = 0;
var /** @type {?} */ staticQueryIds = findStaticQueryIds(template);
var /** @type {?} */ statements = [];
var /** @type {?} */ renderComponentVarName = ((undefined));
if (!component.isHost) {
var /** @type {?} */ template_1 = ((component.template));
var /** @type {?} */ customRenderData = [];
if (template_1.animations && template_1.animations.length) {
customRenderData.push(new LiteralMapEntry('animation', convertValueToOutputAst(template_1.animations), true));
}
var /** @type {?} */ renderComponentVar = variable(rendererTypeName(component.type.reference));
renderComponentVarName = ((renderComponentVar.name));
statements.push(renderComponentVar
.set(importExpr(createIdentifier(Identifiers.createRendererType2))
.callFn([new LiteralMapExpr([
new LiteralMapEntry('encapsulation', literal(template_1.encapsulation)),
new LiteralMapEntry('styles', styles),
new LiteralMapEntry('data', new LiteralMapExpr(customRenderData))
])]))
.toDeclStmt(importType(createIdentifier(Identifiers.RendererType2)), [StmtModifier.Final]));
}
var /** @type {?} */ viewBuilderFactory = function (parent) {
var /** @type {?} */ embeddedViewIndex = embeddedViewCount++;
return new ViewBuilder(parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory);
};
var /** @type {?} */ visitor = viewBuilderFactory(null);
visitor.visitAll([], template);
statements.push.apply(statements, visitor.build());
return new ViewCompileResult(statements, visitor.viewName, renderComponentVarName);
};
return ViewCompiler;
}());
ViewCompiler.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
ViewCompiler.ctorParameters = function () { return [
{ type: CompilerConfig, },
{ type: ElementSchemaRegistry, },
]; };
var LOG_VAR = variable('l');
var VIEW_VAR = variable('v');
var CHECK_VAR = variable('ck');
var COMP_VAR = variable('co');
var EVENT_NAME_VAR = variable('en');
var ALLOW_DEFAULT_VAR = variable("ad");
var ViewBuilder = (function () {
/**
* @param {?} parent
* @param {?} component
* @param {?} embeddedViewIndex
* @param {?} usedPipes
* @param {?} staticQueryIds
* @param {?} viewBuilderFactory
*/
function ViewBuilder(parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory) {
this.parent = parent;
this.component = component;
this.embeddedViewIndex = embeddedViewIndex;
this.usedPipes = usedPipes;
this.staticQueryIds = staticQueryIds;
this.viewBuilderFactory = viewBuilderFactory;
this.nodes = [];
this.purePipeNodeIndices = Object.create(null);
this.refNodeIndices = Object.create(null);
this.variables = [];
this.children = [];
// TODO(tbosch): The old view compiler used to use an `any` type
// for the context in any embedded view. We keep this behaivor for now
// to be able to introduce the new view compiler without too many errors.
this.compType =
this.embeddedViewIndex > 0 ? DYNAMIC_TYPE : importType(this.component.type);
}
Object.defineProperty(ViewBuilder.prototype, "viewName", {
/**
* @return {?}
*/
get: function () {
return viewClassName(this.component.type.reference, this.embeddedViewIndex);
},
enumerable: true,
configurable: true
});
/**
* @param {?} variables
* @param {?} astNodes
* @return {?}
*/
ViewBuilder.prototype.visitAll = function (variables, astNodes) {
var _this = this;
this.variables = variables;
// create the pipes for the pure pipes immediately, so that we know their indices.
if (!this.parent) {
this.usedPipes.forEach(function (pipe) {
if (pipe.pure) {
_this.purePipeNodeIndices[pipe.name] = _this._createPipe(null, pipe);
}
});
}
if (!this.parent) {
var /** @type {?} */ queryIds_1 = staticViewQueryIds(this.staticQueryIds);
this.component.viewQueries.forEach(function (query, queryIndex) {
// Note: queries start with id 1 so we can use the number in a Bloom filter!
var /** @type {?} */ queryId = queryIndex + 1;
var /** @type {?} */ bindingType = query.first ? 0 /* First */ : 1;
var /** @type {?} */ flags = 67108864 /* TypeViewQuery */ | calcStaticDynamicQueryFlags(queryIds_1, queryId, query.first);
_this.nodes.push(function () { return ({
sourceSpan: null,
nodeFlags: flags,
nodeDef: importExpr(createIdentifier(Identifiers.queryDef)).callFn([
literal(flags), literal(queryId),
new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType))])
])
}); });
});
}
templateVisitAll(this, astNodes);
if (this.parent && (astNodes.length === 0 || needsAdditionalRootNode(astNodes))) {
// if the view is an embedded view, then we need to add an additional root node in some cases
this.nodes.push(function () { return ({
sourceSpan: null,
nodeFlags: 1 /* TypeElement */,
nodeDef: importExpr(createIdentifier(Identifiers.anchorDef)).callFn([
literal(0 /* None */), NULL_EXPR, NULL_EXPR, literal(0)
])
}); });
}
};
/**
* @param {?=} targetStatements
* @return {?}
*/
ViewBuilder.prototype.build = function (targetStatements) {
if (targetStatements === void 0) { targetStatements = []; }
this.children.forEach(function (child) { return child.build(targetStatements); });
var _a = this._createNodeExpressions(), updateRendererStmts = _a.updateRendererStmts, updateDirectivesStmts = _a.updateDirectivesStmts, nodeDefExprs = _a.nodeDefExprs;
var /** @type {?} */ updateRendererFn = this._createUpdateFn(updateRendererStmts);
var /** @type {?} */ updateDirectivesFn = this._createUpdateFn(updateDirectivesStmts);
var /** @type {?} */ viewFlags = 0;
if (!this.parent && this.component.changeDetection === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_4" /* ChangeDetectionStrategy */].OnPush) {
viewFlags |= 2 /* OnPush */;
}
var /** @type {?} */ viewFactory = new DeclareFunctionStmt(this.viewName, [new FnParam(/** @type {?} */ ((LOG_VAR.name)))], [new ReturnStatement(importExpr(createIdentifier(Identifiers.viewDef)).callFn([
literal(viewFlags),
literalArr(nodeDefExprs),
updateDirectivesFn,
updateRendererFn,
]))], importType(createIdentifier(Identifiers.ViewDefinition)));
targetStatements.push(viewFactory);
return targetStatements;
};
/**
* @param {?} updateStmts
* @return {?}
*/
ViewBuilder.prototype._createUpdateFn = function (updateStmts) {
var /** @type {?} */ updateFn;
if (updateStmts.length > 0) {
var /** @type {?} */ preStmts = [];
if (!this.component.isHost && findReadVarNames(updateStmts).has(/** @type {?} */ ((COMP_VAR.name)))) {
preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
}
updateFn = fn([
new FnParam(/** @type {?} */ ((CHECK_VAR.name)), INFERRED_TYPE),
new FnParam(/** @type {?} */ ((VIEW_VAR.name)), INFERRED_TYPE)
], preStmts.concat(updateStmts), INFERRED_TYPE);
}
else {
updateFn = NULL_EXPR;
}
return updateFn;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitNgContent = function (ast, context) {
// ngContentDef(ngContentIndex: number, index: number): NodeDef;
this.nodes.push(function () { return ({
sourceSpan: ast.sourceSpan,
nodeFlags: 4 /* TypeNgContent */,
nodeDef: importExpr(createIdentifier(Identifiers.ngContentDef)).callFn([
literal(ast.ngContentIndex), literal(ast.index)
])
}); });
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitText = function (ast, context) {
// textDef(ngContentIndex: number, constants: string[]): NodeDef;
this.nodes.push(function () { return ({
sourceSpan: ast.sourceSpan,
nodeFlags: 2 /* TypeText */,
nodeDef: importExpr(createIdentifier(Identifiers.textDef)).callFn([
literal(ast.ngContentIndex), literalArr([literal(ast.value)])
])
}); });
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitBoundText = function (ast, context) {
var _this = this;
var /** @type {?} */ nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array
this.nodes.push(/** @type {?} */ ((null)));
var /** @type {?} */ astWithSource = (ast.value);
var /** @type {?} */ inter = (astWithSource.ast);
var /** @type {?} */ updateRendererExpressions = inter.expressions.map(function (expr, bindingIndex) { return _this._preprocessUpdateExpression({ nodeIndex: nodeIndex, bindingIndex: bindingIndex, sourceSpan: ast.sourceSpan, context: COMP_VAR, value: expr }); });
// textDef(ngContentIndex: number, constants: string[]): NodeDef;
this.nodes[nodeIndex] = function () { return ({
sourceSpan: ast.sourceSpan,
nodeFlags: 2 /* TypeText */,
nodeDef: importExpr(createIdentifier(Identifiers.textDef)).callFn([
literal(ast.ngContentIndex), literalArr(inter.strings.map(function (s) { return literal(s); }))
]),
updateRenderer: updateRendererExpressions
}); };
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
var _this = this;
var /** @type {?} */ nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array
this.nodes.push(/** @type {?} */ ((null)));
var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, queryMatchesExpr = _a.queryMatchesExpr, hostEvents = _a.hostEvents;
var /** @type {?} */ childVisitor = this.viewBuilderFactory(this);
this.children.push(childVisitor);
childVisitor.visitAll(ast.variables, ast.children);
var /** @type {?} */ childCount = this.nodes.length - nodeIndex - 1;
// anchorDef(
// flags: NodeFlags, matchedQueries: [string, QueryValueType][], ngContentIndex: number,
// childCount: number, handleEventFn?: ElementHandleEventFn, templateFactory?:
// ViewDefinitionFactory): NodeDef;
this.nodes[nodeIndex] = function () { return ({
sourceSpan: ast.sourceSpan,
nodeFlags: 1 /* TypeElement */ | flags,
nodeDef: importExpr(createIdentifier(Identifiers.anchorDef)).callFn([
literal(flags),
queryMatchesExpr,
literal(ast.ngContentIndex),
literal(childCount),
_this._createElementHandleEventFn(nodeIndex, hostEvents),
variable(childVisitor.viewName),
])
}); };
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitElement = function (ast, context) {
var _this = this;
var /** @type {?} */ nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array so we can add children
this.nodes.push(/** @type {?} */ ((null)));
// Using a null element name creates an anchor.
var /** @type {?} */ elName = isNgContainer(ast.name) ? null : ast.name;
var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, usedEvents = _a.usedEvents, queryMatchesExpr = _a.queryMatchesExpr, dirHostBindings = _a.hostBindings, hostEvents = _a.hostEvents;
var /** @type {?} */ inputDefs = [];
var /** @type {?} */ updateRendererExpressions = [];
var /** @type {?} */ outputDefs = [];
if (elName) {
var /** @type {?} */ hostBindings = ast.inputs
.map(function (inputAst) { return ({
context: /** @type {?} */ (COMP_VAR),
inputAst: inputAst,
dirAst: /** @type {?} */ (null),
}); })
.concat(dirHostBindings);
if (hostBindings.length) {
updateRendererExpressions =
hostBindings.map(function (hostBinding, bindingIndex) { return _this._preprocessUpdateExpression({
context: hostBinding.context,
nodeIndex: nodeIndex,
bindingIndex: bindingIndex,
sourceSpan: hostBinding.inputAst.sourceSpan,
value: hostBinding.inputAst.value
}); });
inputDefs = hostBindings.map(function (hostBinding) { return elementBindingDef(hostBinding.inputAst, hostBinding.dirAst); });
}
outputDefs = usedEvents.map(function (_a) {
var target = _a[0], eventName = _a[1];
return literalArr([literal(target), literal(eventName)]);
});
}
templateVisitAll(this, ast.children);
var /** @type {?} */ childCount = this.nodes.length - nodeIndex - 1;
var /** @type {?} */ compAst = ast.directives.find(function (dirAst) { return dirAst.directive.isComponent; });
var /** @type {?} */ compRendererType = NULL_EXPR;
var /** @type {?} */ compView = NULL_EXPR;
if (compAst) {
compView = importExpr({ reference: compAst.directive.componentViewType });
compRendererType = importExpr({ reference: compAst.directive.rendererType });
}
// elementDef(
// flags: NodeFlags, matchedQueriesDsl: [string | number, QueryValueType][],
// ngContentIndex: number, childCount: number, namespaceAndName: string,
// fixedAttrs: [string, string][] = [],
// bindings?: [BindingFlags, string, string | SecurityContext][],
// outputs?: ([OutputType.ElementOutput | OutputType.DirectiveHostOutput, string, string])[],
// handleEvent?: ElementHandleEventFn,
// componentView?: () => ViewDefinition, componentRendererType?: RendererType2): NodeDef;
this.nodes[nodeIndex] = function () { return ({
sourceSpan: ast.sourceSpan,
nodeFlags: 1 /* TypeElement */ | flags,
nodeDef: importExpr(createIdentifier(Identifiers.elementDef)).callFn([
literal(flags),
queryMatchesExpr,
literal(ast.ngContentIndex),
literal(childCount),
literal(elName),
elName ? fixedAttrsDef(ast) : NULL_EXPR,
inputDefs.length ? literalArr(inputDefs) : NULL_EXPR,
outputDefs.length ? literalArr(outputDefs) : NULL_EXPR,
_this._createElementHandleEventFn(nodeIndex, hostEvents),
compView,
compRendererType,
]),
updateRenderer: updateRendererExpressions
}); };
};
/**
* @param {?} nodeIndex
* @param {?} ast
* @return {?}
*/
ViewBuilder.prototype._visitElementOrTemplate = function (nodeIndex, ast) {
var _this = this;
var /** @type {?} */ flags = 0;
if (ast.hasViewContainer) {
flags |= 8388608 /* EmbeddedViews */;
}
var /** @type {?} */ usedEvents = new Map();
ast.outputs.forEach(function (event) {
var _a = elementEventNameAndTarget(event, null), name = _a.name, target = _a.target;
usedEvents.set(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_58" /* ɵelementEventFullName */])(target, name), [target, name]);
});
ast.directives.forEach(function (dirAst) {
dirAst.hostEvents.forEach(function (event) {
var _a = elementEventNameAndTarget(event, dirAst), name = _a.name, target = _a.target;
usedEvents.set(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_58" /* ɵelementEventFullName */])(target, name), [target, name]);
});
});
var /** @type {?} */ hostBindings = [];
var /** @type {?} */ hostEvents = [];
var /** @type {?} */ componentFactoryResolverProvider = createComponentFactoryResolver(ast.directives);
if (componentFactoryResolverProvider) {
this._visitProvider(componentFactoryResolverProvider, ast.queryMatches);
}
ast.providers.forEach(function (providerAst, providerIndex) {
var /** @type {?} */ dirAst = ((undefined));
var /** @type {?} */ dirIndex = ((undefined));
ast.directives.forEach(function (localDirAst, i) {
if (localDirAst.directive.type.reference === tokenReference(providerAst.token)) {
dirAst = localDirAst;
dirIndex = i;
}
});
if (dirAst) {
var _a = _this._visitDirective(providerAst, dirAst, dirIndex, nodeIndex, ast.references, ast.queryMatches, usedEvents, /** @type {?} */ ((_this.staticQueryIds.get(/** @type {?} */ (ast))))), dirHostBindings = _a.hostBindings, dirHostEvents = _a.hostEvents;
hostBindings.push.apply(hostBindings, dirHostBindings);
hostEvents.push.apply(hostEvents, dirHostEvents);
}
else {
_this._visitProvider(providerAst, ast.queryMatches);
}
});
var /** @type {?} */ queryMatchExprs = [];
ast.queryMatches.forEach(function (match) {
var /** @type {?} */ valueType = ((undefined));
if (tokenReference(match.value) === resolveIdentifier(Identifiers.ElementRef)) {
valueType = 0 /* ElementRef */;
}
else if (tokenReference(match.value) === resolveIdentifier(Identifiers.ViewContainerRef)) {
valueType = 3 /* ViewContainerRef */;
}
else if (tokenReference(match.value) === resolveIdentifier(Identifiers.TemplateRef)) {
valueType = 2 /* TemplateRef */;
}
if (valueType != null) {
queryMatchExprs.push(literalArr([literal(match.queryId), literal(valueType)]));
}
});
ast.references.forEach(function (ref) {
var /** @type {?} */ valueType = ((undefined));
if (!ref.value) {
valueType = 1 /* RenderElement */;
}
else if (tokenReference(ref.value) === resolveIdentifier(Identifiers.TemplateRef)) {
valueType = 2 /* TemplateRef */;
}
if (valueType != null) {
_this.refNodeIndices[ref.name] = nodeIndex;
queryMatchExprs.push(literalArr([literal(ref.name), literal(valueType)]));
}
});
ast.outputs.forEach(function (outputAst) {
hostEvents.push({ context: COMP_VAR, eventAst: outputAst, dirAst: /** @type {?} */ ((null)) });
});
return {
flags: flags,
usedEvents: Array.from(usedEvents.values()),
queryMatchesExpr: queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
hostBindings: hostBindings,
hostEvents: hostEvents
};
};
/**
* @param {?} providerAst
* @param {?} dirAst
* @param {?} directiveIndex
* @param {?} elementNodeIndex
* @param {?} refs
* @param {?} queryMatches
* @param {?} usedEvents
* @param {?} queryIds
* @return {?}
*/
ViewBuilder.prototype._visitDirective = function (providerAst, dirAst, directiveIndex, elementNodeIndex, refs, queryMatches, usedEvents, queryIds) {
var _this = this;
var /** @type {?} */ nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array so we can add children
this.nodes.push(/** @type {?} */ ((null)));
dirAst.directive.queries.forEach(function (query, queryIndex) {
var /** @type {?} */ queryId = dirAst.contentQueryStartId + queryIndex;
var /** @type {?} */ flags = 33554432 /* TypeContentQuery */ | calcStaticDynamicQueryFlags(queryIds, queryId, query.first);
var /** @type {?} */ bindingType = query.first ? 0 /* First */ : 1;
_this.nodes.push(function () { return ({
sourceSpan: dirAst.sourceSpan,
nodeFlags: flags,
nodeDef: importExpr(createIdentifier(Identifiers.queryDef)).callFn([
literal(flags), literal(queryId),
new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType))])
]),
}); });
});
// Note: the operation below might also create new nodeDefs,
// but we don't want them to be a child of a directive,
// as they might be a provider/pipe on their own.
// I.e. we only allow queries as children of directives nodes.
var /** @type {?} */ childCount = this.nodes.length - nodeIndex - 1;
var _a = this._visitProviderOrDirective(providerAst, queryMatches), flags = _a.flags, queryMatchExprs = _a.queryMatchExprs, providerExpr = _a.providerExpr, depsExpr = _a.depsExpr;
refs.forEach(function (ref) {
if (ref.value && tokenReference(ref.value) === tokenReference(providerAst.token)) {
_this.refNodeIndices[ref.name] = nodeIndex;
queryMatchExprs.push(literalArr([literal(ref.name), literal(4 /* Provider */)]));
}
});
if (dirAst.directive.isComponent) {
flags |= 16384 /* Component */;
}
var /** @type {?} */ inputDefs = dirAst.inputs.map(function (inputAst, inputIndex) {
var /** @type {?} */ mapValue = literalArr([literal(inputIndex), literal(inputAst.directiveName)]);
// Note: it's important to not quote the key so that we can capture renames by minifiers!
return new LiteralMapEntry(inputAst.directiveName, mapValue, false);
});
var /** @type {?} */ outputDefs = [];
var /** @type {?} */ dirMeta = dirAst.directive;
Object.keys(dirMeta.outputs).forEach(function (propName) {
var /** @type {?} */ eventName = dirMeta.outputs[propName];
if (usedEvents.has(eventName)) {
// Note: it's important to not quote the key so that we can capture renames by minifiers!
outputDefs.push(new LiteralMapEntry(propName, literal(eventName), false));
}
});
var /** @type {?} */ updateDirectiveExpressions = [];
if (dirAst.inputs.length || (flags & (131072 /* DoCheck */ | 32768 /* OnInit */)) > 0) {
updateDirectiveExpressions =
dirAst.inputs.map(function (input, bindingIndex) { return _this._preprocessUpdateExpression({
nodeIndex: nodeIndex,
bindingIndex: bindingIndex,
sourceSpan: input.sourceSpan,
context: COMP_VAR,
value: input.value
}); });
}
var /** @type {?} */ dirContextExpr = importExpr(createIdentifier(Identifiers.nodeValue)).callFn([
VIEW_VAR, literal(nodeIndex)
]);
var /** @type {?} */ hostBindings = dirAst.hostProperties.map(function (inputAst) { return ({
context: dirContextExpr,
dirAst: dirAst,
inputAst: inputAst,
}); });
var /** @type {?} */ hostEvents = dirAst.hostEvents.map(function (hostEventAst) { return ({
context: dirContextExpr,
eventAst: hostEventAst, dirAst: dirAst,
}); });
// directiveDef(
// flags: NodeFlags, matchedQueries: [string, QueryValueType][], childCount: number, ctor:
// any,
// deps: ([DepFlags, any] | any)[], props?: {[name: string]: [number, string]},
// outputs?: {[name: string]: string}, component?: () => ViewDefinition): NodeDef;
this.nodes[nodeIndex] = function () { return ({
sourceSpan: dirAst.sourceSpan,
nodeFlags: 8192 /* TypeDirective */ | flags,
nodeDef: importExpr(createIdentifier(Identifiers.directiveDef)).callFn([
literal(flags), queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
literal(childCount), providerExpr, depsExpr,
inputDefs.length ? new LiteralMapExpr(inputDefs) : NULL_EXPR,
outputDefs.length ? new LiteralMapExpr(outputDefs) : NULL_EXPR
]),
updateDirectives: updateDirectiveExpressions,
directive: dirAst.directive.type,
}); };
return { hostBindings: hostBindings, hostEvents: hostEvents };
};
/**
* @param {?} providerAst
* @param {?} queryMatches
* @return {?}
*/
ViewBuilder.prototype._visitProvider = function (providerAst, queryMatches) {
var /** @type {?} */ nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array so we can add children
this.nodes.push(/** @type {?} */ ((null)));
var _a = this._visitProviderOrDirective(providerAst, queryMatches), flags = _a.flags, queryMatchExprs = _a.queryMatchExprs, providerExpr = _a.providerExpr, depsExpr = _a.depsExpr;
// providerDef(
// flags: NodeFlags, matchedQueries: [string, QueryValueType][], token:any,
// value: any, deps: ([DepFlags, any] | any)[]): NodeDef;
this.nodes[nodeIndex] = function () { return ({
sourceSpan: providerAst.sourceSpan,
nodeFlags: flags,
nodeDef: importExpr(createIdentifier(Identifiers.providerDef)).callFn([
literal(flags), queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
tokenExpr(providerAst.token), providerExpr, depsExpr
])
}); };
};
/**
* @param {?} providerAst
* @param {?} queryMatches
* @return {?}
*/
ViewBuilder.prototype._visitProviderOrDirective = function (providerAst, queryMatches) {
var /** @type {?} */ flags = 0;
if (!providerAst.eager) {
flags |= 2048 /* LazyProvider */;
}
if (providerAst.providerType === ProviderAstType.PrivateService) {
flags |= 4096 /* PrivateProvider */;
}
providerAst.lifecycleHooks.forEach(function (lifecycleHook) {
// for regular providers, we only support ngOnDestroy
if (lifecycleHook === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnDestroy ||
providerAst.providerType === ProviderAstType.Directive ||
providerAst.providerType === ProviderAstType.Component) {
flags |= lifecycleHookToNodeFlag(lifecycleHook);
}
});
var /** @type {?} */ queryMatchExprs = [];
queryMatches.forEach(function (match) {
if (tokenReference(match.value) === tokenReference(providerAst.token)) {
queryMatchExprs.push(literalArr([literal(match.queryId), literal(4 /* Provider */)]));
}
});
var _a = providerDef(providerAst), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, providerType = _a.flags;
return { flags: flags | providerType, queryMatchExprs: queryMatchExprs, providerExpr: providerExpr, depsExpr: depsExpr };
};
/**
* @param {?} name
* @return {?}
*/
ViewBuilder.prototype.getLocal = function (name) {
if (name == EventHandlerVars.event.name) {
return EventHandlerVars.event;
}
var /** @type {?} */ currViewExpr = VIEW_VAR;
for (var /** @type {?} */ currBuilder = this; currBuilder; currBuilder = currBuilder.parent,
currViewExpr = currViewExpr.prop('parent').cast(DYNAMIC_TYPE)) {
// check references
var /** @type {?} */ refNodeIndex = currBuilder.refNodeIndices[name];
if (refNodeIndex != null) {
return importExpr(createIdentifier(Identifiers.nodeValue)).callFn([
currViewExpr, literal(refNodeIndex)
]);
}
// check variables
var /** @type {?} */ varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
if (varAst) {
var /** @type {?} */ varValue = varAst.value || IMPLICIT_TEMPLATE_VAR;
return currViewExpr.prop('context').prop(varValue);
}
}
return null;
};
/**
* @param {?} sourceSpan
* @param {?} argCount
* @return {?}
*/
ViewBuilder.prototype.createLiteralArrayConverter = function (sourceSpan, argCount) {
if (argCount === 0) {
var /** @type {?} */ valueExpr_1 = importExpr(createIdentifier(Identifiers.EMPTY_ARRAY));
return function () { return valueExpr_1; };
}
var /** @type {?} */ nodeIndex = this.nodes.length;
// pureArrayDef(argCount: number): NodeDef;
this.nodes.push(function () { return ({
sourceSpan: sourceSpan,
nodeFlags: 16 /* TypePureArray */,
nodeDef: importExpr(createIdentifier(Identifiers.pureArrayDef)).callFn([literal(argCount)])
}); });
return function (args) { return callCheckStmt(nodeIndex, args); };
};
/**
* @param {?} sourceSpan
* @param {?} keys
* @return {?}
*/
ViewBuilder.prototype.createLiteralMapConverter = function (sourceSpan, keys) {
if (keys.length === 0) {
var /** @type {?} */ valueExpr_2 = importExpr(createIdentifier(Identifiers.EMPTY_MAP));
return function () { return valueExpr_2; };
}
var /** @type {?} */ nodeIndex = this.nodes.length;
// function pureObjectDef(propertyNames: string[]): NodeDef
this.nodes.push(function () { return ({
sourceSpan: sourceSpan,
nodeFlags: 32 /* TypePureObject */,
nodeDef: importExpr(createIdentifier(Identifiers.pureObjectDef))
.callFn([literalArr(keys.map(function (key) { return literal(key); }))])
}); });
return function (args) { return callCheckStmt(nodeIndex, args); };
};
/**
* @param {?} expression
* @param {?} name
* @param {?} argCount
* @return {?}
*/
ViewBuilder.prototype.createPipeConverter = function (expression, name, argCount) {
var /** @type {?} */ pipe = ((this.usedPipes.find(function (pipeSummary) { return pipeSummary.name === name; })));
if (pipe.pure) {
var /** @type {?} */ nodeIndex_1 = this.nodes.length;
// function purePipeDef(argCount: number): NodeDef;
this.nodes.push(function () { return ({
sourceSpan: expression.sourceSpan,
nodeFlags: 64 /* TypePurePipe */,
nodeDef: importExpr(createIdentifier(Identifiers.purePipeDef))
.callFn([literal(argCount)])
}); });
// find underlying pipe in the component view
var /** @type {?} */ compViewExpr = VIEW_VAR;
var /** @type {?} */ compBuilder = this;
while (compBuilder.parent) {
compBuilder = compBuilder.parent;
compViewExpr = compViewExpr.prop('parent').cast(DYNAMIC_TYPE);
}
var /** @type {?} */ pipeNodeIndex = compBuilder.purePipeNodeIndices[name];
var /** @type {?} */ pipeValueExpr_1 = importExpr(createIdentifier(Identifiers.nodeValue)).callFn([
compViewExpr, literal(pipeNodeIndex)
]);
return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, callCheckStmt(nodeIndex_1, [pipeValueExpr_1].concat(args))); };
}
else {
var /** @type {?} */ nodeIndex = this._createPipe(expression.sourceSpan, pipe);
var /** @type {?} */ nodeValueExpr_1 = importExpr(createIdentifier(Identifiers.nodeValue)).callFn([
VIEW_VAR, literal(nodeIndex)
]);
return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, nodeValueExpr_1.callMethod('transform', args)); };
}
};
/**
* @param {?} sourceSpan
* @param {?} pipe
* @return {?}
*/
ViewBuilder.prototype._createPipe = function (sourceSpan, pipe) {
var /** @type {?} */ nodeIndex = this.nodes.length;
var /** @type {?} */ flags = 0;
pipe.type.lifecycleHooks.forEach(function (lifecycleHook) {
// for pipes, we only support ngOnDestroy
if (lifecycleHook === __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnDestroy) {
flags |= lifecycleHookToNodeFlag(lifecycleHook);
}
});
var /** @type {?} */ depExprs = pipe.type.diDeps.map(depDef);
// function pipeDef(
// flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef
this.nodes.push(function () { return ({
sourceSpan: sourceSpan,
nodeFlags: 8 /* TypePipe */,
nodeDef: importExpr(createIdentifier(Identifiers.pipeDef)).callFn([
literal(flags), importExpr(pipe.type), literalArr(depExprs)
])
}); });
return nodeIndex;
};
/**
* @param {?} expression
* @return {?}
*/
ViewBuilder.prototype._preprocessUpdateExpression = function (expression) {
var _this = this;
return {
nodeIndex: expression.nodeIndex,
bindingIndex: expression.bindingIndex,
sourceSpan: expression.sourceSpan,
context: expression.context,
value: convertPropertyBindingBuiltins({
createLiteralArrayConverter: function (argCount) { return _this.createLiteralArrayConverter(expression.sourceSpan, argCount); },
createLiteralMapConverter: function (keys) { return _this.createLiteralMapConverter(expression.sourceSpan, keys); },
createPipeConverter: function (name, argCount) { return _this.createPipeConverter(expression, name, argCount); }
}, expression.value)
};
};
/**
* @return {?}
*/
ViewBuilder.prototype._createNodeExpressions = function () {
var /** @type {?} */ self = this;
var /** @type {?} */ updateBindingCount = 0;
var /** @type {?} */ updateRendererStmts = [];
var /** @type {?} */ updateDirectivesStmts = [];
var /** @type {?} */ nodeDefExprs = this.nodes.map(function (factory, nodeIndex) {
var _a = factory(), nodeDef = _a.nodeDef, nodeFlags = _a.nodeFlags, updateDirectives = _a.updateDirectives, updateRenderer = _a.updateRenderer, sourceSpan = _a.sourceSpan;
if (updateRenderer) {
updateRendererStmts.push.apply(updateRendererStmts, createUpdateStatements(nodeIndex, sourceSpan, updateRenderer, false));
}
if (updateDirectives) {
updateDirectivesStmts.push.apply(updateDirectivesStmts, createUpdateStatements(nodeIndex, sourceSpan, updateDirectives, (nodeFlags & (131072 /* DoCheck */ | 32768 /* OnInit */)) > 0));
}
// We use a comma expression to call the log function before
// the nodeDef function, but still use the result of the nodeDef function
// as the value.
// Note: We only add the logger to elements / text nodes,
// so we don't generate too much code.
var /** @type {?} */ logWithNodeDef = nodeFlags & 3 /* CatRenderNode */ ?
new CommaExpr([LOG_VAR.callFn([]).callFn([]), nodeDef]) :
nodeDef;
return applySourceSpanToExpressionIfNeeded(logWithNodeDef, sourceSpan);
});
return { updateRendererStmts: updateRendererStmts, updateDirectivesStmts: updateDirectivesStmts, nodeDefExprs: nodeDefExprs };
/**
* @param {?} nodeIndex
* @param {?} sourceSpan
* @param {?} expressions
* @param {?} allowEmptyExprs
* @return {?}
*/
function createUpdateStatements(nodeIndex, sourceSpan, expressions, allowEmptyExprs) {
var /** @type {?} */ updateStmts = [];
var /** @type {?} */ exprs = expressions.map(function (_a) {
var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
var /** @type {?} */ bindingId = "" + updateBindingCount++;
var /** @type {?} */ nameResolver = context === COMP_VAR ? self : null;
var _b = convertPropertyBinding(nameResolver, context, value, bindingId), stmts = _b.stmts, currValExpr = _b.currValExpr;
updateStmts.push.apply(updateStmts, stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); }));
return applySourceSpanToExpressionIfNeeded(currValExpr, sourceSpan);
});
if (expressions.length || allowEmptyExprs) {
updateStmts.push(applySourceSpanToStatementIfNeeded(callCheckStmt(nodeIndex, exprs).toStmt(), sourceSpan));
}
return updateStmts;
}
};
/**
* @param {?} nodeIndex
* @param {?} handlers
* @return {?}
*/
ViewBuilder.prototype._createElementHandleEventFn = function (nodeIndex, handlers) {
var _this = this;
var /** @type {?} */ handleEventStmts = [];
var /** @type {?} */ handleEventBindingCount = 0;
handlers.forEach(function (_a) {
var context = _a.context, eventAst = _a.eventAst, dirAst = _a.dirAst;
var /** @type {?} */ bindingId = "" + handleEventBindingCount++;
var /** @type {?} */ nameResolver = context === COMP_VAR ? _this : null;
var _b = convertActionBinding(nameResolver, context, eventAst.handler, bindingId), stmts = _b.stmts, allowDefault = _b.allowDefault;
var /** @type {?} */ trueStmts = stmts;
if (allowDefault) {
trueStmts.push(ALLOW_DEFAULT_VAR.set(allowDefault.and(ALLOW_DEFAULT_VAR)).toStmt());
}
var _c = elementEventNameAndTarget(eventAst, dirAst), eventTarget = _c.target, eventName = _c.name;
var /** @type {?} */ fullEventName = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_58" /* ɵelementEventFullName */])(eventTarget, eventName);
handleEventStmts.push(applySourceSpanToStatementIfNeeded(new IfStmt(literal(fullEventName).identical(EVENT_NAME_VAR), trueStmts), eventAst.sourceSpan));
});
var /** @type {?} */ handleEventFn;
if (handleEventStmts.length > 0) {
var /** @type {?} */ preStmts = [ALLOW_DEFAULT_VAR.set(literal(true)).toDeclStmt(BOOL_TYPE)];
if (!this.component.isHost && findReadVarNames(handleEventStmts).has(/** @type {?} */ ((COMP_VAR.name)))) {
preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
}
handleEventFn = fn([
new FnParam(/** @type {?} */ ((VIEW_VAR.name)), INFERRED_TYPE),
new FnParam(/** @type {?} */ ((EVENT_NAME_VAR.name)), INFERRED_TYPE),
new FnParam(/** @type {?} */ ((EventHandlerVars.event.name)), INFERRED_TYPE)
], preStmts.concat(handleEventStmts, [new ReturnStatement(ALLOW_DEFAULT_VAR)]), INFERRED_TYPE);
}
else {
handleEventFn = NULL_EXPR;
}
return handleEventFn;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitDirective = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitReference = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitVariable = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitEvent = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
ViewBuilder.prototype.visitAttr = function (ast, context) { };
return ViewBuilder;
}());
/**
* @param {?} providerAst
* @return {?}
*/
function providerDef(providerAst) {
return providerAst.multiProvider ?
multiProviderDef(providerAst.providers) :
singleProviderDef(providerAst.providerType, providerAst.providers[0]);
}
/**
* @param {?} providers
* @return {?}
*/
function multiProviderDef(providers) {
var /** @type {?} */ allDepDefs = [];
var /** @type {?} */ allParams = [];
var /** @type {?} */ exprs = providers.map(function (provider, providerIndex) {
var /** @type {?} */ expr;
if (provider.useClass) {
var /** @type {?} */ depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
expr = importExpr(provider.useClass).instantiate(depExprs);
}
else if (provider.useFactory) {
var /** @type {?} */ depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
expr = importExpr(provider.useFactory).callFn(depExprs);
}
else if (provider.useExisting) {
var /** @type {?} */ depExprs = convertDeps(providerIndex, [{ token: provider.useExisting }]);
expr = depExprs[0];
}
else {
expr = convertValueToOutputAst(provider.useValue);
}
return expr;
});
var /** @type {?} */ providerExpr = fn(allParams, [new ReturnStatement(literalArr(exprs))], INFERRED_TYPE);
return { providerExpr: providerExpr, flags: 512 /* TypeFactoryProvider */, depsExpr: literalArr(allDepDefs) };
/**
* @param {?} providerIndex
* @param {?} deps
* @return {?}
*/
function convertDeps(providerIndex, deps) {
return deps.map(function (dep, depIndex) {
var /** @type {?} */ paramName = "p" + providerIndex + "_" + depIndex;
allParams.push(new FnParam(paramName, DYNAMIC_TYPE));
allDepDefs.push(depDef(dep));
return variable(paramName);
});
}
}
/**
* @param {?} providerType
* @param {?} providerMeta
* @return {?}
*/
function singleProviderDef(providerType, providerMeta) {
var /** @type {?} */ providerExpr;
var /** @type {?} */ flags;
var /** @type {?} */ deps;
if (providerType === ProviderAstType.Directive || providerType === ProviderAstType.Component) {
providerExpr = importExpr(/** @type {?} */ ((providerMeta.useClass)));
flags = 8192 /* TypeDirective */;
deps = providerMeta.deps || ((providerMeta.useClass)).diDeps;
}
else {
if (providerMeta.useClass) {
providerExpr = importExpr(providerMeta.useClass);
flags = 256 /* TypeClassProvider */;
deps = providerMeta.deps || providerMeta.useClass.diDeps;
}
else if (providerMeta.useFactory) {
providerExpr = importExpr(providerMeta.useFactory);
flags = 512 /* TypeFactoryProvider */;
deps = providerMeta.deps || providerMeta.useFactory.diDeps;
}
else if (providerMeta.useExisting) {
providerExpr = NULL_EXPR;
flags = 1024 /* TypeUseExistingProvider */;
deps = [{ token: providerMeta.useExisting }];
}
else {
providerExpr = convertValueToOutputAst(providerMeta.useValue);
flags = 128 /* TypeValueProvider */;
deps = [];
}
}
var /** @type {?} */ depsExpr = literalArr(deps.map(function (dep) { return depDef(dep); }));
return { providerExpr: providerExpr, flags: flags, depsExpr: depsExpr };
}
/**
* @param {?} tokenMeta
* @return {?}
*/
function tokenExpr(tokenMeta) {
return tokenMeta.identifier ? importExpr(tokenMeta.identifier) : literal(tokenMeta.value);
}
/**
* @param {?} dep
* @return {?}
*/
function depDef(dep) {
// Note: the following fields have already been normalized out by provider_analyzer:
// - isAttribute, isSelf, isHost
var /** @type {?} */ expr = dep.isValue ? convertValueToOutputAst(dep.value) : tokenExpr(/** @type {?} */ ((dep.token)));
var /** @type {?} */ flags = 0;
if (dep.isSkipSelf) {
flags |= 1 /* SkipSelf */;
}
if (dep.isOptional) {
flags |= 2 /* Optional */;
}
if (dep.isValue) {
flags |= 8 /* Value */;
}
return flags === 0 /* None */ ? expr : literalArr([literal(flags), expr]);
}
/**
* @param {?} astNodes
* @return {?}
*/
function needsAdditionalRootNode(astNodes) {
var /** @type {?} */ lastAstNode = astNodes[astNodes.length - 1];
if (lastAstNode instanceof EmbeddedTemplateAst) {
return lastAstNode.hasViewContainer;
}
if (lastAstNode instanceof ElementAst) {
if (isNgContainer(lastAstNode.name) && lastAstNode.children.length) {
return needsAdditionalRootNode(lastAstNode.children);
}
return lastAstNode.hasViewContainer;
}
return lastAstNode instanceof NgContentAst;
}
/**
* @param {?} lifecycleHook
* @return {?}
*/
function lifecycleHookToNodeFlag(lifecycleHook) {
var /** @type {?} */ nodeFlag = 0;
switch (lifecycleHook) {
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].AfterContentChecked:
nodeFlag = 1048576 /* AfterContentChecked */;
break;
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].AfterContentInit:
nodeFlag = 524288 /* AfterContentInit */;
break;
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].AfterViewChecked:
nodeFlag = 4194304 /* AfterViewChecked */;
break;
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].AfterViewInit:
nodeFlag = 2097152 /* AfterViewInit */;
break;
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].DoCheck:
nodeFlag = 131072 /* DoCheck */;
break;
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnChanges:
nodeFlag = 262144 /* OnChanges */;
break;
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnDestroy:
nodeFlag = 65536 /* OnDestroy */;
break;
case __WEBPACK_IMPORTED_MODULE_0__angular_core__["_52" /* ɵLifecycleHooks */].OnInit:
nodeFlag = 32768 /* OnInit */;
break;
}
return nodeFlag;
}
/**
* @param {?} inputAst
* @param {?} dirAst
* @return {?}
*/
function elementBindingDef(inputAst, dirAst) {
switch (inputAst.type) {
case PropertyBindingType.Attribute:
return literalArr([
literal(1 /* TypeElementAttribute */), literal(inputAst.name),
literal(inputAst.securityContext)
]);
case PropertyBindingType.Property:
return literalArr([
literal(8 /* TypeProperty */), literal(inputAst.name),
literal(inputAst.securityContext)
]);
case PropertyBindingType.Animation:
var /** @type {?} */ bindingType = 8 /* TypeProperty */ |
(dirAst && dirAst.directive.isComponent ? 32 /* SyntheticHostProperty */ :
16 /* SyntheticProperty */);
return literalArr([
literal(bindingType), literal('@' + inputAst.name), literal(inputAst.securityContext)
]);
case PropertyBindingType.Class:
return literalArr([literal(2 /* TypeElementClass */), literal(inputAst.name), NULL_EXPR]);
case PropertyBindingType.Style:
return literalArr([
literal(4 /* TypeElementStyle */), literal(inputAst.name), literal(inputAst.unit)
]);
}
}
/**
* @param {?} elementAst
* @return {?}
*/
function fixedAttrsDef(elementAst) {
var /** @type {?} */ mapResult = Object.create(null);
elementAst.attrs.forEach(function (attrAst) { mapResult[attrAst.name] = attrAst.value; });
elementAst.directives.forEach(function (dirAst) {
Object.keys(dirAst.directive.hostAttributes).forEach(function (name) {
var /** @type {?} */ value = dirAst.directive.hostAttributes[name];
var /** @type {?} */ prevValue = mapResult[name];
mapResult[name] = prevValue != null ? mergeAttributeValue(name, prevValue, value) : value;
});
});
// Note: We need to sort to get a defined output order
// for tests and for caching generated artifacts...
return literalArr(Object.keys(mapResult).sort().map(function (attrName) { return literalArr([literal(attrName), literal(mapResult[attrName])]); }));
}
/**
* @param {?} attrName
* @param {?} attrValue1
* @param {?} attrValue2
* @return {?}
*/
function mergeAttributeValue(attrName, attrValue1, attrValue2) {
if (attrName == CLASS_ATTR$1 || attrName == STYLE_ATTR) {
return attrValue1 + " " + attrValue2;
}
else {
return attrValue2;
}
}
/**
* @param {?} nodeIndex
* @param {?} exprs
* @return {?}
*/
function callCheckStmt(nodeIndex, exprs) {
if (exprs.length > 10) {
return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(1 /* Dynamic */), literalArr(exprs)]);
}
else {
return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(0 /* Inline */)].concat(exprs));
}
}
/**
* @param {?} nodeIndex
* @param {?} bindingIdx
* @param {?} expr
* @return {?}
*/
function callUnwrapValue(nodeIndex, bindingIdx, expr) {
return importExpr(createIdentifier(Identifiers.unwrapValue)).callFn([
VIEW_VAR, literal(nodeIndex), literal(bindingIdx), expr
]);
}
/**
* @param {?} nodes
* @param {?=} result
* @return {?}
*/
function findStaticQueryIds(nodes, result) {
if (result === void 0) { result = new Map(); }
nodes.forEach(function (node) {
var /** @type {?} */ staticQueryIds = new Set();
var /** @type {?} */ dynamicQueryIds = new Set();
var /** @type {?} */ queryMatches = ((undefined));
if (node instanceof ElementAst) {
findStaticQueryIds(node.children, result);
node.children.forEach(function (child) {
var /** @type {?} */ childData = ((result.get(child)));
childData.staticQueryIds.forEach(function (queryId) { return staticQueryIds.add(queryId); });
childData.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
});
queryMatches = node.queryMatches;
}
else if (node instanceof EmbeddedTemplateAst) {
findStaticQueryIds(node.children, result);
node.children.forEach(function (child) {
var /** @type {?} */ childData = ((result.get(child)));
childData.staticQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
childData.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
});
queryMatches = node.queryMatches;
}
if (queryMatches) {
queryMatches.forEach(function (match) { return staticQueryIds.add(match.queryId); });
}
dynamicQueryIds.forEach(function (queryId) { return staticQueryIds.delete(queryId); });
result.set(node, { staticQueryIds: staticQueryIds, dynamicQueryIds: dynamicQueryIds });
});
return result;
}
/**
* @param {?} nodeStaticQueryIds
* @return {?}
*/
function staticViewQueryIds(nodeStaticQueryIds) {
var /** @type {?} */ staticQueryIds = new Set();
var /** @type {?} */ dynamicQueryIds = new Set();
Array.from(nodeStaticQueryIds.values()).forEach(function (entry) {
entry.staticQueryIds.forEach(function (queryId) { return staticQueryIds.add(queryId); });
entry.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
});
dynamicQueryIds.forEach(function (queryId) { return staticQueryIds.delete(queryId); });
return { staticQueryIds: staticQueryIds, dynamicQueryIds: dynamicQueryIds };
}
/**
* @param {?} directives
* @return {?}
*/
function createComponentFactoryResolver(directives) {
var /** @type {?} */ componentDirMeta = directives.find(function (dirAst) { return dirAst.directive.isComponent; });
if (componentDirMeta && componentDirMeta.directive.entryComponents.length) {
var /** @type {?} */ entryComponentFactories = componentDirMeta.directive.entryComponents.map(function (entryComponent) { return importExpr({ reference: entryComponent.componentFactory }); });
var /** @type {?} */ token = createIdentifierToken(Identifiers.ComponentFactoryResolver);
var /** @type {?} */ classMeta = {
diDeps: [
{ isValue: true, value: literalArr(entryComponentFactories) },
{ token: token, isSkipSelf: true, isOptional: true },
{ token: createIdentifierToken(Identifiers.NgModuleRef) },
],
lifecycleHooks: [],
reference: resolveIdentifier(Identifiers.CodegenComponentFactoryResolver)
};
return new ProviderAst(token, false, true, [{ token: token, multi: false, useClass: classMeta }], ProviderAstType.PrivateService, [], componentDirMeta.sourceSpan);
}
return null;
}
/**
* @param {?} eventAst
* @param {?} dirAst
* @return {?}
*/
function elementEventNameAndTarget(eventAst, dirAst) {
if (eventAst.isAnimation) {
return {
name: "@" + eventAst.name + "." + eventAst.phase,
target: dirAst && dirAst.directive.isComponent ? 'component' : null
};
}
else {
return eventAst;
}
}
/**
* @param {?} queryIds
* @param {?} queryId
* @param {?} isFirst
* @return {?}
*/
function calcStaticDynamicQueryFlags(queryIds, queryId, isFirst) {
var /** @type {?} */ flags = 0;
// Note: We only make queries static that query for a single item.
// This is because of backwards compatibility with the old view compiler...
if (isFirst && (queryIds.staticQueryIds.has(queryId) || !queryIds.dynamicQueryIds.has(queryId))) {
flags |= 134217728 /* StaticQuery */;
}
else {
flags |= 268435456 /* DynamicQuery */;
}
return flags;
}
/**
* @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
*/
var GeneratedFile = (function () {
/**
* @param {?} srcFileUrl
* @param {?} genFileUrl
* @param {?} source
*/
function GeneratedFile(srcFileUrl, genFileUrl, source) {
this.srcFileUrl = srcFileUrl;
this.genFileUrl = genFileUrl;
this.source = source;
}
return GeneratedFile;
}());
/**
* @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
*/
/**
* @param {?} summaryResolver
* @param {?} symbolResolver
* @param {?} symbols
* @param {?} types
* @return {?}
*/
function serializeSummaries(summaryResolver, symbolResolver, symbols, types) {
var /** @type {?} */ serializer = new Serializer$1(symbolResolver, summaryResolver);
// for symbols, we use everything except for the class metadata itself
// (we keep the statics though), as the class metadata is contained in the
// CompileTypeSummary.
symbols.forEach(function (resolvedSymbol) { return serializer.addOrMergeSummary({ symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata }); });
// Add summaries that are referenced by the given symbols (transitively)
// Note: the serializer.symbols array might be growing while
// we execute the loop!
for (var /** @type {?} */ processedIndex = 0; processedIndex < serializer.symbols.length; processedIndex++) {
var /** @type {?} */ symbol = serializer.symbols[processedIndex];
if (summaryResolver.isLibraryFile(symbol.filePath)) {
var /** @type {?} */ summary = summaryResolver.resolveSummary(symbol);
if (!summary) {
// some symbols might originate from a plain typescript library
// that just exported .d.ts and .metadata.json files, i.e. where no summary
// files were created.
var /** @type {?} */ resolvedSymbol = symbolResolver.resolveSymbol(symbol);
if (resolvedSymbol) {
summary = { symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata };
}
}
if (summary) {
serializer.addOrMergeSummary(summary);
}
}
}
// Add type summaries.
// Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
// as the type summaries already contain the transitive data that they require
// (in a minimal way).
types.forEach(function (typeSummary) {
serializer.addOrMergeSummary({ symbol: typeSummary.type.reference, metadata: null, type: typeSummary });
if (typeSummary.summaryKind === CompileSummaryKind.NgModule) {
var /** @type {?} */ ngModuleSummary = (typeSummary);
ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach(function (id) {
var /** @type {?} */ symbol = id.reference;
if (summaryResolver.isLibraryFile(symbol.filePath)) {
var /** @type {?} */ summary = summaryResolver.resolveSummary(symbol);
if (summary) {
serializer.addOrMergeSummary(summary);
}
}
});
}
});
return serializer.serialize();
}
/**
* @param {?} symbolCache
* @param {?} json
* @return {?}
*/
function deserializeSummaries(symbolCache, json) {
var /** @type {?} */ deserializer = new Deserializer(symbolCache);
return deserializer.deserialize(json);
}
var Serializer$1 = (function (_super) {
__extends(Serializer$1, _super);
/**
* @param {?} symbolResolver
* @param {?} summaryResolver
*/
function Serializer$1(symbolResolver, summaryResolver) {
var _this = _super.call(this) || this;
_this.symbolResolver = symbolResolver;
_this.summaryResolver = summaryResolver;
// Note: This only contains symbols without members.
_this.symbols = [];
_this.indexBySymbol = new Map();
_this.processedSummaryBySymbol = new Map();
_this.processedSummaries = [];
return _this;
}
/**
* @param {?} summary
* @return {?}
*/
Serializer$1.prototype.addOrMergeSummary = function (summary) {
var /** @type {?} */ symbolMeta = summary.metadata;
if (symbolMeta && symbolMeta.__symbolic === 'class') {
// For classes, we keep everything except their class decorators.
// We need to keep e.g. the ctor args, method names, method decorators
// so that the class can be extended in another compilation unit.
// We don't keep the class decorators as
// 1) they refer to data
// that should not cause a rebuild of downstream compilation units
// (e.g. inline templates of @Component, or @NgModule.declarations)
// 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
var /** @type {?} */ clone_1 = {};
Object.keys(symbolMeta).forEach(function (propName) {
if (propName !== 'decorators') {
clone_1[propName] = symbolMeta[propName];
}
});
symbolMeta = clone_1;
}
var /** @type {?} */ processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
if (!processedSummary) {
processedSummary = this.processValue({ symbol: summary.symbol });
this.processedSummaries.push(processedSummary);
this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
}
// Note: == on purpose to compare with undefined!
if (processedSummary.metadata == null && symbolMeta != null) {
processedSummary.metadata = this.processValue(symbolMeta);
}
// Note: == on purpose to compare with undefined!
if (processedSummary.type == null && summary.type != null) {
processedSummary.type = this.processValue(summary.type);
}
};
/**
* @return {?}
*/
Serializer$1.prototype.serialize = function () {
var _this = this;
var /** @type {?} */ exportAs = [];
var /** @type {?} */ json = JSON.stringify({
summaries: this.processedSummaries,
symbols: this.symbols.map(function (symbol, index) {
symbol.assertNoMembers();
var /** @type {?} */ importAs = ((undefined));
if (_this.summaryResolver.isLibraryFile(symbol.filePath)) {
importAs = symbol.name + "_" + index;
exportAs.push({ symbol: symbol, exportAs: importAs });
}
return {
__symbol: index,
name: symbol.name,
// We convert the source filenames tinto output filenames,
// as the generated summary file will be used when teh current
// compilation unit is used as a library
filePath: _this.summaryResolver.getLibraryFileName(symbol.filePath),
importAs: importAs
};
})
});
return { json: json, exportAs: exportAs };
};
/**
* @param {?} value
* @return {?}
*/
Serializer$1.prototype.processValue = function (value) { return visitValue(value, this, null); };
/**
* @param {?} value
* @param {?} context
* @return {?}
*/
Serializer$1.prototype.visitOther = function (value, context) {
if (value instanceof StaticSymbol) {
var /** @type {?} */ baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
var /** @type {?} */ index = this.indexBySymbol.get(baseSymbol);
// Note: == on purpose to compare with undefined!
if (index == null) {
index = this.indexBySymbol.size;
this.indexBySymbol.set(baseSymbol, index);
this.symbols.push(baseSymbol);
}
return { __symbol: index, members: value.members };
}
};
return Serializer$1;
}(ValueTransformer));
var Deserializer = (function (_super) {
__extends(Deserializer, _super);
/**
* @param {?} symbolCache
*/
function Deserializer(symbolCache) {
var _this = _super.call(this) || this;
_this.symbolCache = symbolCache;
return _this;
}
/**
* @param {?} json
* @return {?}
*/
Deserializer.prototype.deserialize = function (json) {
var _this = this;
var /** @type {?} */ data = JSON.parse(json);
var /** @type {?} */ importAs = [];
this.symbols = [];
data.symbols.forEach(function (serializedSymbol) {
var /** @type {?} */ symbol = _this.symbolCache.get(serializedSymbol.filePath, serializedSymbol.name);
_this.symbols.push(symbol);
if (serializedSymbol.importAs) {
importAs.push({ symbol: symbol, importAs: serializedSymbol.importAs });
}
});
var /** @type {?} */ summaries = visitValue(data.summaries, this, null);
return { summaries: summaries, importAs: importAs };
};
/**
* @param {?} map
* @param {?} context
* @return {?}
*/
Deserializer.prototype.visitStringMap = function (map, context) {
if ('__symbol' in map) {
var /** @type {?} */ baseSymbol = this.symbols[map['__symbol']];
var /** @type {?} */ members = map['members'];
return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
baseSymbol;
}
else {
return _super.prototype.visitStringMap.call(this, map, context);
}
};
return Deserializer;
}(ValueTransformer));
/**
* @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
*/
var AotCompiler = (function () {
/**
* @param {?} _config
* @param {?} _host
* @param {?} _metadataResolver
* @param {?} _templateParser
* @param {?} _styleCompiler
* @param {?} _viewCompiler
* @param {?} _ngModuleCompiler
* @param {?} _outputEmitter
* @param {?} _summaryResolver
* @param {?} _localeId
* @param {?} _translationFormat
* @param {?} _genFilePreamble
* @param {?} _symbolResolver
*/
function AotCompiler(_config, _host, _metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _ngModuleCompiler, _outputEmitter, _summaryResolver, _localeId, _translationFormat, _genFilePreamble, _symbolResolver) {
this._config = _config;
this._host = _host;
this._metadataResolver = _metadataResolver;
this._templateParser = _templateParser;
this._styleCompiler = _styleCompiler;
this._viewCompiler = _viewCompiler;
this._ngModuleCompiler = _ngModuleCompiler;
this._outputEmitter = _outputEmitter;
this._summaryResolver = _summaryResolver;
this._localeId = _localeId;
this._translationFormat = _translationFormat;
this._genFilePreamble = _genFilePreamble;
this._symbolResolver = _symbolResolver;
}
/**
* @return {?}
*/
AotCompiler.prototype.clearCache = function () { this._metadataResolver.clearCache(); };
/**
* @param {?} rootFiles
* @return {?}
*/
AotCompiler.prototype.compileAll = function (rootFiles) {
var _this = this;
var /** @type {?} */ programSymbols = extractProgramSymbols(this._symbolResolver, rootFiles, this._host);
var _a = analyzeAndValidateNgModules(programSymbols, this._host, this._metadataResolver), ngModuleByPipeOrDirective = _a.ngModuleByPipeOrDirective, files = _a.files, ngModules = _a.ngModules;
return Promise
.all(ngModules.map(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
.then(function () {
var /** @type {?} */ sourceModules = files.map(function (file) { return _this._compileSrcFile(file.srcUrl, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables); });
return flatten(sourceModules);
});
};
/**
* @param {?} srcFileUrl
* @param {?} ngModuleByPipeOrDirective
* @param {?} directives
* @param {?} pipes
* @param {?} ngModules
* @param {?} injectables
* @return {?}
*/
AotCompiler.prototype._compileSrcFile = function (srcFileUrl, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables) {
var _this = this;
var /** @type {?} */ fileSuffix = splitTypescriptSuffix(srcFileUrl)[1];
var /** @type {?} */ statements = [];
var /** @type {?} */ exportedVars = [];
var /** @type {?} */ generatedFiles = [];
generatedFiles.push(this._createSummary(srcFileUrl, directives, pipes, ngModules, injectables, statements, exportedVars));
// compile all ng modules
exportedVars.push.apply(exportedVars, ngModules.map(function (ngModuleType) { return _this._compileModule(ngModuleType, statements); }));
// compile components
directives.forEach(function (dirType) {
var /** @type {?} */ compMeta = _this._metadataResolver.getDirectiveMetadata(/** @type {?} */ (dirType));
if (!compMeta.isComponent) {
return Promise.resolve(null);
}
var /** @type {?} */ ngModule = ngModuleByPipeOrDirective.get(dirType);
if (!ngModule) {
throw new Error("Internal Error: cannot determine the module for component " + identifierName(compMeta.type) + "!");
}
_assertComponent(compMeta);
// compile styles
var /** @type {?} */ stylesCompileResults = _this._styleCompiler.compileComponent(compMeta);
stylesCompileResults.externalStylesheets.forEach(function (compiledStyleSheet) {
generatedFiles.push(_this._codgenStyles(srcFileUrl, compiledStyleSheet, fileSuffix));
});
// compile components
var /** @type {?} */ compViewVars = _this._compileComponent(compMeta, ngModule, ngModule.transitiveModule.directives, stylesCompileResults.componentStylesheet, fileSuffix, statements);
exportedVars.push(_this._compileComponentFactory(compMeta, ngModule, fileSuffix, statements), compViewVars.viewClassVar, compViewVars.compRenderTypeVar);
});
if (statements.length > 0) {
var /** @type {?} */ srcModule = this._codegenSourceModule(srcFileUrl, ngfactoryFilePath(srcFileUrl), statements, exportedVars);
generatedFiles.unshift(srcModule);
}
return generatedFiles;
};
/**
* @param {?} srcFileUrl
* @param {?} directives
* @param {?} pipes
* @param {?} ngModules
* @param {?} injectables
* @param {?} targetStatements
* @param {?} targetExportedVars
* @return {?}
*/
AotCompiler.prototype._createSummary = function (srcFileUrl, directives, pipes, ngModules, injectables, targetStatements, targetExportedVars) {
var _this = this;
var /** @type {?} */ symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileUrl)
.map(function (symbol) { return _this._symbolResolver.resolveSymbol(symbol); });
var /** @type {?} */ typeSummaries = ngModules.map(function (ref) { return ((_this._metadataResolver.getNgModuleSummary(ref))); }).concat(directives.map(function (ref) { return ((_this._metadataResolver.getDirectiveSummary(ref))); }), pipes.map(function (ref) { return ((_this._metadataResolver.getPipeSummary(ref))); }), injectables.map(function (ref) { return ((_this._metadataResolver.getInjectableSummary(ref))); }));
var _a = serializeSummaries(this._summaryResolver, this._symbolResolver, symbolSummaries, typeSummaries), json = _a.json, exportAs = _a.exportAs;
exportAs.forEach(function (entry) {
targetStatements.push(variable(entry.exportAs).set(importExpr({ reference: entry.symbol })).toDeclStmt());
targetExportedVars.push(entry.exportAs);
});
return new GeneratedFile(srcFileUrl, summaryFileName(srcFileUrl), json);
};
/**
* @param {?} ngModuleType
* @param {?} targetStatements
* @return {?}
*/
AotCompiler.prototype._compileModule = function (ngModuleType, targetStatements) {
var /** @type {?} */ ngModule = ((this._metadataResolver.getNgModuleMetadata(ngModuleType)));
var /** @type {?} */ providers = [];
if (this._localeId) {
providers.push({
token: createIdentifierToken(Identifiers.LOCALE_ID),
useValue: this._localeId,
});
}
if (this._translationFormat) {
providers.push({
token: createIdentifierToken(Identifiers.TRANSLATIONS_FORMAT),
useValue: this._translationFormat
});
}
var /** @type {?} */ appCompileResult = this._ngModuleCompiler.compile(ngModule, providers);
targetStatements.push.apply(targetStatements, appCompileResult.statements);
return appCompileResult.ngModuleFactoryVar;
};
/**
* @param {?} compMeta
* @param {?} ngModule
* @param {?} fileSuffix
* @param {?} targetStatements
* @return {?}
*/
AotCompiler.prototype._compileComponentFactory = function (compMeta, ngModule, fileSuffix, targetStatements) {
var /** @type {?} */ hostType = this._metadataResolver.getHostComponentType(compMeta.type.reference);
var /** @type {?} */ hostMeta = createHostComponentMeta(hostType, compMeta, this._metadataResolver.getHostComponentViewClass(hostType));
var /** @type {?} */ hostViewFactoryVar = this._compileComponent(hostMeta, ngModule, [compMeta.type], null, fileSuffix, targetStatements)
.viewClassVar;
var /** @type {?} */ compFactoryVar = componentFactoryName(compMeta.type.reference);
var /** @type {?} */ inputsExprs = [];
for (var /** @type {?} */ propName in compMeta.inputs) {
var /** @type {?} */ templateName = compMeta.inputs[propName];
// Don't quote so that the key gets minified...
inputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
}
var /** @type {?} */ outputsExprs = [];
for (var /** @type {?} */ propName in compMeta.outputs) {
var /** @type {?} */ templateName = compMeta.outputs[propName];
// Don't quote so that the key gets minified...
outputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
}
targetStatements.push(variable(compFactoryVar)
.set(importExpr(createIdentifier(Identifiers.createComponentFactory)).callFn([
literal(compMeta.selector), importExpr(compMeta.type),
variable(hostViewFactoryVar), new LiteralMapExpr(inputsExprs),
new LiteralMapExpr(outputsExprs),
literalArr(/** @type {?} */ ((compMeta.template)).ngContentSelectors.map(function (selector) { return literal(selector); }))
]))
.toDeclStmt(importType(createIdentifier(Identifiers.ComponentFactory), [/** @type {?} */ ((importType(compMeta.type)))], [TypeModifier.Const]), [StmtModifier.Final]));
return compFactoryVar;
};
/**
* @param {?} compMeta
* @param {?} ngModule
* @param {?} directiveIdentifiers
* @param {?} componentStyles
* @param {?} fileSuffix
* @param {?} targetStatements
* @return {?}
*/
AotCompiler.prototype._compileComponent = function (compMeta, ngModule, directiveIdentifiers, componentStyles, fileSuffix, targetStatements) {
var _this = this;
var /** @type {?} */ directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
var /** @type {?} */ pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
var _a = this._templateParser.parse(compMeta, /** @type {?} */ ((((compMeta.template)).template)), directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, /** @type {?} */ ((compMeta.template)))), parsedTemplate = _a.template, usedPipes = _a.pipes;
var /** @type {?} */ stylesExpr = componentStyles ? variable(componentStyles.stylesVar) : literalArr([]);
var /** @type {?} */ viewResult = this._viewCompiler.compileComponent(compMeta, parsedTemplate, stylesExpr, usedPipes);
if (componentStyles) {
targetStatements.push.apply(targetStatements, _resolveStyleStatements(this._symbolResolver, componentStyles, fileSuffix));
}
targetStatements.push.apply(targetStatements, viewResult.statements);
return { viewClassVar: viewResult.viewClassVar, compRenderTypeVar: viewResult.rendererTypeVar };
};
/**
* @param {?} fileUrl
* @param {?} stylesCompileResult
* @param {?} fileSuffix
* @return {?}
*/
AotCompiler.prototype._codgenStyles = function (fileUrl, stylesCompileResult, fileSuffix) {
_resolveStyleStatements(this._symbolResolver, stylesCompileResult, fileSuffix);
return this._codegenSourceModule(fileUrl, _stylesModuleUrl(/** @type {?} */ ((stylesCompileResult.meta.moduleUrl)), stylesCompileResult.isShimmed, fileSuffix), stylesCompileResult.statements, [stylesCompileResult.stylesVar]);
};
/**
* @param {?} srcFileUrl
* @param {?} genFileUrl
* @param {?} statements
* @param {?} exportedVars
* @return {?}
*/
AotCompiler.prototype._codegenSourceModule = function (srcFileUrl, genFileUrl, statements, exportedVars) {
return new GeneratedFile(srcFileUrl, genFileUrl, this._outputEmitter.emitStatements(sourceUrl(srcFileUrl), genFileUrl, statements, exportedVars, this._genFilePreamble));
};
return AotCompiler;
}());
/**
* @param {?} reflector
* @param {?} compileResult
* @param {?} fileSuffix
* @return {?}
*/
function _resolveStyleStatements(reflector, compileResult, fileSuffix) {
compileResult.dependencies.forEach(function (dep) {
dep.valuePlaceholder.reference = reflector.getStaticSymbol(_stylesModuleUrl(dep.moduleUrl, dep.isShimmed, fileSuffix), dep.name);
});
return compileResult.statements;
}
/**
* @param {?} stylesheetUrl
* @param {?} shim
* @param {?} suffix
* @return {?}
*/
function _stylesModuleUrl(stylesheetUrl, shim, suffix) {
return "" + stylesheetUrl + (shim ? '.shim' : '') + ".ngstyle" + suffix;
}
/**
* @param {?} meta
* @return {?}
*/
function _assertComponent(meta) {
if (!meta.isComponent) {
throw new Error("Could not compile '" + identifierName(meta.type) + "' because it is not a component.");
}
}
/**
* @param {?} programStaticSymbols
* @param {?} host
* @param {?} metadataResolver
* @return {?}
*/
function analyzeNgModules(programStaticSymbols, host, metadataResolver) {
var _a = _createNgModules(programStaticSymbols, host, metadataResolver), ngModules = _a.ngModules, symbolsMissingModule = _a.symbolsMissingModule;
return _analyzeNgModules(programStaticSymbols, ngModules, symbolsMissingModule, metadataResolver);
}
/**
* @param {?} programStaticSymbols
* @param {?} host
* @param {?} metadataResolver
* @return {?}
*/
function analyzeAndValidateNgModules(programStaticSymbols, host, metadataResolver) {
var /** @type {?} */ result = analyzeNgModules(programStaticSymbols, host, metadataResolver);
if (result.symbolsMissingModule && result.symbolsMissingModule.length) {
var /** @type {?} */ messages = result.symbolsMissingModule.map(function (s) { return "Cannot determine the module for class " + s.name + " in " + s.filePath + "! Add " + s.name + " to the NgModule to fix it."; });
throw syntaxError(messages.join('\n'));
}
return result;
}
/**
* @param {?} programSymbols
* @param {?} ngModuleMetas
* @param {?} symbolsMissingModule
* @param {?} metadataResolver
* @return {?}
*/
function _analyzeNgModules(programSymbols, ngModuleMetas, symbolsMissingModule, metadataResolver) {
var /** @type {?} */ moduleMetasByRef = new Map();
ngModuleMetas.forEach(function (ngModule) { return moduleMetasByRef.set(ngModule.type.reference, ngModule); });
var /** @type {?} */ ngModuleByPipeOrDirective = new Map();
var /** @type {?} */ ngModulesByFile = new Map();
var /** @type {?} */ ngDirectivesByFile = new Map();
var /** @type {?} */ ngPipesByFile = new Map();
var /** @type {?} */ ngInjectablesByFile = new Map();
var /** @type {?} */ filePaths = new Set();
// Make sure we produce an analyzed file for each input file
programSymbols.forEach(function (symbol) {
var /** @type {?} */ filePath = symbol.filePath;
filePaths.add(filePath);
if (metadataResolver.isInjectable(symbol)) {
ngInjectablesByFile.set(filePath, (ngInjectablesByFile.get(filePath) || []).concat(symbol));
}
});
// Looping over all modules to construct:
// - a map from file to modules `ngModulesByFile`,
// - a map from file to directives `ngDirectivesByFile`,
// - a map from file to pipes `ngPipesByFile`,
// - a map from directive/pipe to module `ngModuleByPipeOrDirective`.
ngModuleMetas.forEach(function (ngModuleMeta) {
var /** @type {?} */ srcFileUrl = ngModuleMeta.type.reference.filePath;
filePaths.add(srcFileUrl);
ngModulesByFile.set(srcFileUrl, (ngModulesByFile.get(srcFileUrl) || []).concat(ngModuleMeta.type.reference));
ngModuleMeta.declaredDirectives.forEach(function (dirIdentifier) {
var /** @type {?} */ fileUrl = dirIdentifier.reference.filePath;
filePaths.add(fileUrl);
ngDirectivesByFile.set(fileUrl, (ngDirectivesByFile.get(fileUrl) || []).concat(dirIdentifier.reference));
ngModuleByPipeOrDirective.set(dirIdentifier.reference, ngModuleMeta);
});
ngModuleMeta.declaredPipes.forEach(function (pipeIdentifier) {
var /** @type {?} */ fileUrl = pipeIdentifier.reference.filePath;
filePaths.add(fileUrl);
ngPipesByFile.set(fileUrl, (ngPipesByFile.get(fileUrl) || []).concat(pipeIdentifier.reference));
ngModuleByPipeOrDirective.set(pipeIdentifier.reference, ngModuleMeta);
});
});
var /** @type {?} */ files = [];
filePaths.forEach(function (srcUrl) {
var /** @type {?} */ directives = ngDirectivesByFile.get(srcUrl) || [];
var /** @type {?} */ pipes = ngPipesByFile.get(srcUrl) || [];
var /** @type {?} */ ngModules = ngModulesByFile.get(srcUrl) || [];
var /** @type {?} */ injectables = ngInjectablesByFile.get(srcUrl) || [];
files.push({ srcUrl: srcUrl, directives: directives, pipes: pipes, ngModules: ngModules, injectables: injectables });
});
return {
// map directive/pipe to module
ngModuleByPipeOrDirective: ngModuleByPipeOrDirective,
// list modules and directives for every source file
files: files,
ngModules: ngModuleMetas, symbolsMissingModule: symbolsMissingModule
};
}
/**
* @param {?} staticSymbolResolver
* @param {?} files
* @param {?} host
* @return {?}
*/
function extractProgramSymbols(staticSymbolResolver, files, host) {
var /** @type {?} */ staticSymbols = [];
files.filter(function (fileName) { return host.isSourceFile(fileName); }).forEach(function (sourceFile) {
staticSymbolResolver.getSymbolsOf(sourceFile).forEach(function (symbol) {
var /** @type {?} */ resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
var /** @type {?} */ symbolMeta = resolvedSymbol.metadata;
if (symbolMeta) {
if (symbolMeta.__symbolic != 'error') {
// Ignore symbols that are only included to record error information.
staticSymbols.push(resolvedSymbol.symbol);
}
}
});
});
return staticSymbols;
}
/**
* @param {?} programStaticSymbols
* @param {?} host
* @param {?} metadataResolver
* @return {?}
*/
function _createNgModules(programStaticSymbols, host, metadataResolver) {
var /** @type {?} */ ngModules = new Map();
var /** @type {?} */ programPipesAndDirectives = [];
var /** @type {?} */ ngModulePipesAndDirective = new Set();
var /** @type {?} */ addNgModule = function (staticSymbol) {
if (ngModules.has(staticSymbol) || !host.isSourceFile(staticSymbol.filePath)) {
return false;
}
var /** @type {?} */ ngModule = metadataResolver.getNgModuleMetadata(staticSymbol, false);
if (ngModule) {
ngModules.set(ngModule.type.reference, ngModule);
ngModule.declaredDirectives.forEach(function (dir) { return ngModulePipesAndDirective.add(dir.reference); });
ngModule.declaredPipes.forEach(function (pipe) { return ngModulePipesAndDirective.add(pipe.reference); });
// For every input module add the list of transitively included modules
ngModule.transitiveModule.modules.forEach(function (modMeta) { return addNgModule(modMeta.reference); });
}
return !!ngModule;
};
programStaticSymbols.forEach(function (staticSymbol) {
if (!addNgModule(staticSymbol) &&
(metadataResolver.isDirective(staticSymbol) || metadataResolver.isPipe(staticSymbol))) {
programPipesAndDirectives.push(staticSymbol);
}
});
// Throw an error if any of the program pipe or directives is not declared by a module
var /** @type {?} */ symbolsMissingModule = programPipesAndDirectives.filter(function (s) { return !ngModulePipesAndDirective.has(s); });
return { ngModules: Array.from(ngModules.values()), symbolsMissingModule: symbolsMissingModule };
}
/**
* @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
*/
var StaticAndDynamicReflectionCapabilities = (function () {
/**
* @param {?} staticDelegate
*/
function StaticAndDynamicReflectionCapabilities(staticDelegate) {
this.staticDelegate = staticDelegate;
this.dynamicDelegate = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["_59" /* ɵReflectionCapabilities */]();
}
/**
* @param {?} staticDelegate
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.install = function (staticDelegate) {
__WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */].updateCapabilities(new StaticAndDynamicReflectionCapabilities(staticDelegate));
};
/**
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.isReflectionEnabled = function () { return true; };
/**
* @param {?} type
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.factory = function (type) { return this.dynamicDelegate.factory(type); };
/**
* @param {?} type
* @param {?} lcProperty
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.hasLifecycleHook = function (type, lcProperty) {
return isStaticType(type) ? this.staticDelegate.hasLifecycleHook(type, lcProperty) :
this.dynamicDelegate.hasLifecycleHook(type, lcProperty);
};
/**
* @param {?} type
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.parameters = function (type) {
return isStaticType(type) ? this.staticDelegate.parameters(type) :
this.dynamicDelegate.parameters(type);
};
/**
* @param {?} type
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.annotations = function (type) {
return isStaticType(type) ? this.staticDelegate.annotations(type) :
this.dynamicDelegate.annotations(type);
};
/**
* @param {?} typeOrFunc
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.propMetadata = function (typeOrFunc) {
return isStaticType(typeOrFunc) ? this.staticDelegate.propMetadata(typeOrFunc) :
this.dynamicDelegate.propMetadata(typeOrFunc);
};
/**
* @param {?} name
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.getter = function (name) { return this.dynamicDelegate.getter(name); };
/**
* @param {?} name
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.setter = function (name) { return this.dynamicDelegate.setter(name); };
/**
* @param {?} name
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.method = function (name) { return this.dynamicDelegate.method(name); };
/**
* @param {?} type
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.importUri = function (type) { return ((this.staticDelegate.importUri(type))); };
/**
* @param {?} type
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.resourceUri = function (type) { return this.staticDelegate.resourceUri(type); };
/**
* @param {?} name
* @param {?} moduleUrl
* @param {?} members
* @param {?} runtime
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.resolveIdentifier = function (name, moduleUrl, members, runtime) {
return this.staticDelegate.resolveIdentifier(name, moduleUrl, members);
};
/**
* @param {?} enumIdentifier
* @param {?} name
* @return {?}
*/
StaticAndDynamicReflectionCapabilities.prototype.resolveEnum = function (enumIdentifier, name) {
if (isStaticType(enumIdentifier)) {
return this.staticDelegate.resolveEnum(enumIdentifier, name);
}
else {
return null;
}
};
return StaticAndDynamicReflectionCapabilities;
}());
/**
* @param {?} type
* @return {?}
*/
function isStaticType(type) {
return typeof type === 'object' && type.name && type.filePath;
}
/**
* @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
*/
var ANGULAR_CORE = '@angular/core';
var HIDDEN_KEY = /^\$.*\$$/;
var IGNORE = {
__symbolic: 'ignore'
};
/**
* @param {?} value
* @return {?}
*/
function shouldIgnore(value) {
return value && value.__symbolic == 'ignore';
}
/**
* A static reflector implements enough of the Reflector API that is necessary to compile
* templates statically.
*/
var StaticReflector = (function () {
/**
* @param {?} summaryResolver
* @param {?} symbolResolver
* @param {?=} knownMetadataClasses
* @param {?=} knownMetadataFunctions
* @param {?=} errorRecorder
*/
function StaticReflector(summaryResolver, symbolResolver, knownMetadataClasses, knownMetadataFunctions, errorRecorder) {
if (knownMetadataClasses === void 0) { knownMetadataClasses = []; }
if (knownMetadataFunctions === void 0) { knownMetadataFunctions = []; }
var _this = this;
this.summaryResolver = summaryResolver;
this.symbolResolver = symbolResolver;
this.errorRecorder = errorRecorder;
this.annotationCache = new Map();
this.propertyCache = new Map();
this.parameterCache = new Map();
this.methodCache = new Map();
this.conversionMap = new Map();
this.annotationForParentClassWithSummaryKind = new Map();
this.annotationNames = new Map();
this.initializeConversionMap();
knownMetadataClasses.forEach(function (kc) { return _this._registerDecoratorOrConstructor(_this.getStaticSymbol(kc.filePath, kc.name), kc.ctor); });
knownMetadataFunctions.forEach(function (kf) { return _this._registerFunction(_this.getStaticSymbol(kf.filePath, kf.name), kf.fn); });
this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Directive, [__WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], __WEBPACK_IMPORTED_MODULE_0__angular_core__["_3" /* Component */]]);
this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Pipe, [__WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */]]);
this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.NgModule, [__WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */]]);
this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Injectable, [__WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */], __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], __WEBPACK_IMPORTED_MODULE_0__angular_core__["_3" /* Component */], __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */]]);
this.annotationNames.set(__WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */], 'Directive');
this.annotationNames.set(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_3" /* Component */], 'Component');
this.annotationNames.set(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */], 'Pipe');
this.annotationNames.set(__WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */], 'NgModule');
this.annotationNames.set(__WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */], 'Injectable');
}
/**
* @param {?} typeOrFunc
* @return {?}
*/
StaticReflector.prototype.importUri = function (typeOrFunc) {
var /** @type {?} */ staticSymbol = this.findSymbolDeclaration(typeOrFunc);
return staticSymbol ? staticSymbol.filePath : null;
};
/**
* @param {?} typeOrFunc
* @return {?}
*/
StaticReflector.prototype.resourceUri = function (typeOrFunc) {
var /** @type {?} */ staticSymbol = this.findSymbolDeclaration(typeOrFunc);
return this.symbolResolver.getResourcePath(staticSymbol);
};
/**
* @param {?} name
* @param {?} moduleUrl
* @param {?} members
* @return {?}
*/
StaticReflector.prototype.resolveIdentifier = function (name, moduleUrl, members) {
var /** @type {?} */ importSymbol = this.getStaticSymbol(moduleUrl, name);
var /** @type {?} */ rootSymbol = this.findDeclaration(moduleUrl, name);
if (importSymbol != rootSymbol) {
this.symbolResolver.recordImportAs(rootSymbol, importSymbol);
}
if (members && members.length) {
return this.getStaticSymbol(rootSymbol.filePath, rootSymbol.name, members);
}
return rootSymbol;
};
/**
* @param {?} moduleUrl
* @param {?} name
* @param {?=} containingFile
* @return {?}
*/
StaticReflector.prototype.findDeclaration = function (moduleUrl, name, containingFile) {
return this.findSymbolDeclaration(this.symbolResolver.getSymbolByModule(moduleUrl, name, containingFile));
};
/**
* @param {?} symbol
* @return {?}
*/
StaticReflector.prototype.findSymbolDeclaration = function (symbol) {
var /** @type {?} */ resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
if (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
return this.findSymbolDeclaration(resolvedSymbol.metadata);
}
else {
return symbol;
}
};
/**
* @param {?} enumIdentifier
* @param {?} name
* @return {?}
*/
StaticReflector.prototype.resolveEnum = function (enumIdentifier, name) {
var /** @type {?} */ staticSymbol = enumIdentifier;
var /** @type {?} */ members = (staticSymbol.members || []).concat(name);
return this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name, members);
};
/**
* @param {?} type
* @return {?}
*/
StaticReflector.prototype.annotations = function (type) {
var _this = this;
var /** @type {?} */ annotations = this.annotationCache.get(type);
if (!annotations) {
annotations = [];
var /** @type {?} */ classMetadata = this.getTypeMetadata(type);
var /** @type {?} */ parentType = this.findParentType(type, classMetadata);
if (parentType) {
var /** @type {?} */ parentAnnotations = this.annotations(parentType);
annotations.push.apply(annotations, parentAnnotations);
}
var /** @type {?} */ ownAnnotations_1 = [];
if (classMetadata['decorators']) {
ownAnnotations_1 = this.simplify(type, classMetadata['decorators']);
annotations.push.apply(annotations, ownAnnotations_1);
}
if (parentType && !this.summaryResolver.isLibraryFile(type.filePath) &&
this.summaryResolver.isLibraryFile(parentType.filePath)) {
var /** @type {?} */ summary = this.summaryResolver.resolveSummary(parentType);
if (summary && summary.type) {
var /** @type {?} */ requiredAnnotationTypes = ((this.annotationForParentClassWithSummaryKind.get(/** @type {?} */ ((summary.type.summaryKind)))));
var /** @type {?} */ typeHasRequiredAnnotation = requiredAnnotationTypes.some(function (requiredType) { return ownAnnotations_1.some(function (ann) { return ann instanceof requiredType; }); });
if (!typeHasRequiredAnnotation) {
this.reportError(syntaxError("Class " + type.name + " in " + type.filePath + " extends from a " + CompileSummaryKind[((summary.type.summaryKind))] + " in another compilation unit without duplicating the decorator. " +
("Please add a " + requiredAnnotationTypes.map(function (type) { return _this.annotationNames.get(type); }).join(' or ') + " decorator to the class.")), type);
}
}
}
this.annotationCache.set(type, annotations.filter(function (ann) { return !!ann; }));
}
return annotations;
};
/**
* @param {?} type
* @return {?}
*/
StaticReflector.prototype.propMetadata = function (type) {
var _this = this;
var /** @type {?} */ propMetadata = this.propertyCache.get(type);
if (!propMetadata) {
var /** @type {?} */ classMetadata = this.getTypeMetadata(type);
propMetadata = {};
var /** @type {?} */ parentType = this.findParentType(type, classMetadata);
if (parentType) {
var /** @type {?} */ parentPropMetadata_1 = this.propMetadata(parentType);
Object.keys(parentPropMetadata_1).forEach(function (parentProp) {
((propMetadata))[parentProp] = parentPropMetadata_1[parentProp];
});
}
var /** @type {?} */ members_1 = classMetadata['members'] || {};
Object.keys(members_1).forEach(function (propName) {
var /** @type {?} */ propData = members_1[propName];
var /** @type {?} */ prop = ((propData))
.find(function (a) { return a['__symbolic'] == 'property' || a['__symbolic'] == 'method'; });
var /** @type {?} */ decorators = [];
if (((propMetadata))[propName]) {
decorators.push.apply(decorators, ((propMetadata))[propName]);
} /** @type {?} */
((propMetadata))[propName] = decorators;
if (prop && prop['decorators']) {
decorators.push.apply(decorators, _this.simplify(type, prop['decorators']));
}
});
this.propertyCache.set(type, propMetadata);
}
return propMetadata;
};
/**
* @param {?} type
* @return {?}
*/
StaticReflector.prototype.parameters = function (type) {
if (!(type instanceof StaticSymbol)) {
this.reportError(new Error("parameters received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
return [];
}
try {
var /** @type {?} */ parameters_1 = this.parameterCache.get(type);
if (!parameters_1) {
var /** @type {?} */ classMetadata = this.getTypeMetadata(type);
var /** @type {?} */ parentType = this.findParentType(type, classMetadata);
var /** @type {?} */ members = classMetadata ? classMetadata['members'] : null;
var /** @type {?} */ ctorData = members ? members['__ctor__'] : null;
if (ctorData) {
var /** @type {?} */ ctor = ((ctorData)).find(function (a) { return a['__symbolic'] == 'constructor'; });
var /** @type {?} */ parameterTypes = (this.simplify(type, ctor['parameters'] || []));
var /** @type {?} */ parameterDecorators_1 = (this.simplify(type, ctor['parameterDecorators'] || []));
parameters_1 = [];
parameterTypes.forEach(function (paramType, index) {
var /** @type {?} */ nestedResult = [];
if (paramType) {
nestedResult.push(paramType);
}
var /** @type {?} */ decorators = parameterDecorators_1 ? parameterDecorators_1[index] : null;
if (decorators) {
nestedResult.push.apply(nestedResult, decorators);
} /** @type {?} */
((parameters_1)).push(nestedResult);
});
}
else if (parentType) {
parameters_1 = this.parameters(parentType);
}
if (!parameters_1) {
parameters_1 = [];
}
this.parameterCache.set(type, parameters_1);
}
return parameters_1;
}
catch (e) {
console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
throw e;
}
};
/**
* @param {?} type
* @return {?}
*/
StaticReflector.prototype._methodNames = function (type) {
var /** @type {?} */ methodNames = this.methodCache.get(type);
if (!methodNames) {
var /** @type {?} */ classMetadata = this.getTypeMetadata(type);
methodNames = {};
var /** @type {?} */ parentType = this.findParentType(type, classMetadata);
if (parentType) {
var /** @type {?} */ parentMethodNames_1 = this._methodNames(parentType);
Object.keys(parentMethodNames_1).forEach(function (parentProp) {
((methodNames))[parentProp] = parentMethodNames_1[parentProp];
});
}
var /** @type {?} */ members_2 = classMetadata['members'] || {};
Object.keys(members_2).forEach(function (propName) {
var /** @type {?} */ propData = members_2[propName];
var /** @type {?} */ isMethod = ((propData)).some(function (a) { return a['__symbolic'] == 'method'; }); /** @type {?} */
((methodNames))[propName] = ((methodNames))[propName] || isMethod;
});
this.methodCache.set(type, methodNames);
}
return methodNames;
};
/**
* @param {?} type
* @param {?} classMetadata
* @return {?}
*/
StaticReflector.prototype.findParentType = function (type, classMetadata) {
var /** @type {?} */ parentType = this.trySimplify(type, classMetadata['extends']);
if (parentType instanceof StaticSymbol) {
return parentType;
}
};
/**
* @param {?} type
* @param {?} lcProperty
* @return {?}
*/
StaticReflector.prototype.hasLifecycleHook = function (type, lcProperty) {
if (!(type instanceof StaticSymbol)) {
this.reportError(new Error("hasLifecycleHook received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
}
try {
return !!this._methodNames(type)[lcProperty];
}
catch (e) {
console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
throw e;
}
};
/**
* @param {?} type
* @param {?} ctor
* @return {?}
*/
StaticReflector.prototype._registerDecoratorOrConstructor = function (type, ctor) {
this.conversionMap.set(type, function (context, args) { return new (ctor.bind.apply(ctor, [void 0].concat(args)))(); });
};
/**
* @param {?} type
* @param {?} fn
* @return {?}
*/
StaticReflector.prototype._registerFunction = function (type, fn) {
this.conversionMap.set(type, function (context, args) { return fn.apply(undefined, args); });
};
/**
* @return {?}
*/
StaticReflector.prototype.initializeConversionMap = function () {
this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Injectable'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["l" /* Injectable */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["s" /* SkipSelf */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Inject'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Attribute'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["Z" /* Attribute */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChild'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_60" /* ContentChild */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChildren'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_8" /* ContentChildren */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChild'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_15" /* ViewChild */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChildren'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_61" /* ViewChildren */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Input'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["n" /* Input */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Output'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["t" /* Output */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Pipe'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_1" /* Pipe */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostBinding'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_7" /* HostBinding */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostListener'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_6" /* HostListener */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Directive'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["c" /* Directive */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Component'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_3" /* Component */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'NgModule'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* NgModule */]);
// Note: Some metadata classes can be used directly with Provider.deps.
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["p" /* Host */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["q" /* Self */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["s" /* SkipSelf */]);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */]);
this._registerFunction(this.findDeclaration(ANGULAR_CORE, 'trigger'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_62" /* trigger */]);
this._registerFunction(this.findDeclaration(ANGULAR_CORE, 'state'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_63" /* state */]);
this._registerFunction(this.findDeclaration(ANGULAR_CORE, 'transition'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_64" /* transition */]);
this._registerFunction(this.findDeclaration(ANGULAR_CORE, 'style'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_65" /* style */]);
this._registerFunction(this.findDeclaration(ANGULAR_CORE, 'animate'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_66" /* animate */]);
this._registerFunction(this.findDeclaration(ANGULAR_CORE, 'keyframes'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_67" /* keyframes */]);
this._registerFunction(this.findDeclaration(ANGULAR_CORE, 'sequence'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_68" /* sequence */]);
this._registerFunction(this.findDeclaration(ANGULAR_CORE, 'group'), __WEBPACK_IMPORTED_MODULE_0__angular_core__["_69" /* group */]);
};
/**
* getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
* All types passed to the StaticResolver should be pseudo-types returned by this method.
*
* @param {?} declarationFile the absolute path of the file where the symbol is declared
* @param {?} name the name of the type.
* @param {?=} members
* @return {?}
*/
StaticReflector.prototype.getStaticSymbol = function (declarationFile, name, members) {
return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
};
/**
* @param {?} error
* @param {?} context
* @param {?=} path
* @return {?}
*/
StaticReflector.prototype.reportError = function (error, context, path) {
if (this.errorRecorder) {
this.errorRecorder(error, (context && context.filePath) || path);
}
else {
throw error;
}
};
/**
* Simplify but discard any errors
* @param {?} context
* @param {?} value
* @return {?}
*/
StaticReflector.prototype.trySimplify = function (context, value) {
var /** @type {?} */ originalRecorder = this.errorRecorder;
this.errorRecorder = function (error, fileName) { };
var /** @type {?} */ result = this.simplify(context, value);
this.errorRecorder = originalRecorder;
return result;
};
/**
* \@internal
* @param {?} context
* @param {?} value
* @return {?}
*/
StaticReflector.prototype.simplify = function (context, value) {
var _this = this;
var /** @type {?} */ self = this;
var /** @type {?} */ scope = BindingScope.empty;
var /** @type {?} */ calling = new Map();
/**
* @param {?} context
* @param {?} value
* @param {?} depth
* @return {?}
*/
function simplifyInContext(context, value, depth) {
/**
* @param {?} staticSymbol
* @return {?}
*/
function resolveReferenceValue(staticSymbol) {
var /** @type {?} */ resolvedSymbol = self.symbolResolver.resolveSymbol(staticSymbol);
return resolvedSymbol ? resolvedSymbol.metadata : null;
}
/**
* @param {?} functionSymbol
* @param {?} targetFunction
* @param {?} args
* @return {?}
*/
function simplifyCall(functionSymbol, targetFunction, args) {
if (targetFunction && targetFunction['__symbolic'] == 'function') {
if (calling.get(functionSymbol)) {
throw new Error('Recursion not supported');
}
calling.set(functionSymbol, true);
try {
var /** @type {?} */ value_1 = targetFunction['value'];
if (value_1 && (depth != 0 || value_1.__symbolic != 'error')) {
var /** @type {?} */ parameters = targetFunction['parameters'];
var /** @type {?} */ defaults = targetFunction.defaults;
args = args.map(function (arg) { return simplifyInContext(context, arg, depth + 1); })
.map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
if (defaults && defaults.length > args.length) {
args.push.apply(args, defaults.slice(args.length).map(function (value) { return simplify(value); }));
}
var /** @type {?} */ functionScope = BindingScope.build();
for (var /** @type {?} */ i = 0; i < parameters.length; i++) {
functionScope.define(parameters[i], args[i]);
}
var /** @type {?} */ oldScope = scope;
var /** @type {?} */ result_1;
try {
scope = functionScope.done();
result_1 = simplifyInContext(functionSymbol, value_1, depth + 1);
}
finally {
scope = oldScope;
}
return result_1;
}
}
finally {
calling.delete(functionSymbol);
}
}
if (depth === 0) {
// If depth is 0 we are evaluating the top level expression that is describing element
// decorator. In this case, it is a decorator we don't understand, such as a custom
// non-angular decorator, and we should just ignore it.
return IGNORE;
}
return simplify({ __symbolic: 'error', message: 'Function call not supported', context: functionSymbol });
}
/**
* @param {?} expression
* @return {?}
*/
function simplify(expression) {
if (isPrimitive(expression)) {
return expression;
}
if (expression instanceof Array) {
var /** @type {?} */ result_2 = [];
for (var _i = 0, _a = ((expression)); _i < _a.length; _i++) {
var item = _a[_i];
// Check for a spread expression
if (item && item.__symbolic === 'spread') {
var /** @type {?} */ spreadArray = simplify(item.expression);
if (Array.isArray(spreadArray)) {
for (var _b = 0, spreadArray_1 = spreadArray; _b < spreadArray_1.length; _b++) {
var spreadItem = spreadArray_1[_b];
result_2.push(spreadItem);
}
continue;
}
}
var /** @type {?} */ value_2 = simplify(item);
if (shouldIgnore(value_2)) {
continue;
}
result_2.push(value_2);
}
return result_2;
}
if (expression instanceof StaticSymbol) {
// Stop simplification at builtin symbols
if (expression === self.injectionToken || expression === self.opaqueToken ||
self.conversionMap.has(expression)) {
return expression;
}
else {
var /** @type {?} */ staticSymbol = expression;
var /** @type {?} */ declarationValue = resolveReferenceValue(staticSymbol);
if (declarationValue) {
return simplifyInContext(staticSymbol, declarationValue, depth + 1);
}
else {
return staticSymbol;
}
}
}
if (expression) {
if (expression['__symbolic']) {
var /** @type {?} */ staticSymbol = void 0;
switch (expression['__symbolic']) {
case 'binop':
var /** @type {?} */ left = simplify(expression['left']);
if (shouldIgnore(left))
return left;
var /** @type {?} */ right = simplify(expression['right']);
if (shouldIgnore(right))
return right;
switch (expression['operator']) {
case '&&':
return left && right;
case '||':
return left || right;
case '|':
return left | right;
case '^':
return left ^ right;
case '&':
return left & right;
case '==':
return left == right;
case '!=':
return left != right;
case '===':
return left === right;
case '!==':
return left !== right;
case '<':
return left < right;
case '>':
return left > right;
case '<=':
return left <= right;
case '>=':
return left >= right;
case '<<':
return left << right;
case '>>':
return left >> right;
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '%':
return left % right;
}
return null;
case 'if':
var /** @type {?} */ condition = simplify(expression['condition']);
return condition ? simplify(expression['thenExpression']) :
simplify(expression['elseExpression']);
case 'pre':
var /** @type {?} */ operand = simplify(expression['operand']);
if (shouldIgnore(operand))
return operand;
switch (expression['operator']) {
case '+':
return operand;
case '-':
return -operand;
case '!':
return !operand;
case '~':
return ~operand;
}
return null;
case 'index':
var /** @type {?} */ indexTarget = simplify(expression['expression']);
var /** @type {?} */ index = simplify(expression['index']);
if (indexTarget && isPrimitive(index))
return indexTarget[index];
return null;
case 'select':
var /** @type {?} */ member = expression['member'];
var /** @type {?} */ selectContext = context;
var /** @type {?} */ selectTarget = simplify(expression['expression']);
if (selectTarget instanceof StaticSymbol) {
var /** @type {?} */ members = selectTarget.members.concat(member);
selectContext =
self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
var /** @type {?} */ declarationValue = resolveReferenceValue(selectContext);
if (declarationValue) {
return simplifyInContext(selectContext, declarationValue, depth + 1);
}
else {
return selectContext;
}
}
if (selectTarget && isPrimitive(member))
return simplifyInContext(selectContext, selectTarget[member], depth + 1);
return null;
case 'reference':
// Note: This only has to deal with variable references,
// as symbol references have been converted into StaticSymbols already
// in the StaticSymbolResolver!
var /** @type {?} */ name = expression['name'];
var /** @type {?} */ localValue = scope.resolve(name);
if (localValue != BindingScope.missing) {
return localValue;
}
break;
case 'class':
return context;
case 'function':
return context;
case 'new':
case 'call':
// Determine if the function is a built-in conversion
staticSymbol = simplifyInContext(context, expression['expression'], depth + 1);
if (staticSymbol instanceof StaticSymbol) {
if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
// if somebody calls new InjectionToken, don't create an InjectionToken,
// but rather return the symbol to which the InjectionToken is assigned to.
return context;
}
var /** @type {?} */ argExpressions = expression['arguments'] || [];
var /** @type {?} */ converter = self.conversionMap.get(staticSymbol);
if (converter) {
var /** @type {?} */ args = argExpressions.map(function (arg) { return simplifyInContext(context, arg, depth + 1); })
.map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
return converter(context, args);
}
else {
// Determine if the function is one we can simplify.
var /** @type {?} */ targetFunction = resolveReferenceValue(staticSymbol);
return simplifyCall(staticSymbol, targetFunction, argExpressions);
}
}
return IGNORE;
case 'error':
var /** @type {?} */ message = produceErrorMessage(expression);
if (expression['line']) {
message =
message + " (position " + (expression['line'] + 1) + ":" + (expression['character'] + 1) + " in the original .ts file)";
self.reportError(positionalError(message, context.filePath, expression['line'], expression['character']), context);
}
else {
self.reportError(new Error(message), context);
}
return IGNORE;
case 'ignore':
return expression;
}
return null;
}
return mapStringMap(expression, function (value, name) { return simplify(value); });
}
return IGNORE;
}
try {
return simplify(value);
}
catch (e) {
var /** @type {?} */ members = context.members.length ? "." + context.members.join('.') : '';
var /** @type {?} */ message = e.message + ", resolving symbol " + context.name + members + " in " + context.filePath;
if (e.fileName) {
throw positionalError(message, e.fileName, e.line, e.column);
}
throw syntaxError(message);
}
}
var /** @type {?} */ recordedSimplifyInContext = function (context, value, depth) {
try {
return simplifyInContext(context, value, depth);
}
catch (e) {
_this.reportError(e, context);
}
};
var /** @type {?} */ result = this.errorRecorder ? recordedSimplifyInContext(context, value, 0) :
simplifyInContext(context, value, 0);
if (shouldIgnore(result)) {
return undefined;
}
return result;
};
/**
* @param {?} type
* @return {?}
*/
StaticReflector.prototype.getTypeMetadata = function (type) {
var /** @type {?} */ resolvedSymbol = this.symbolResolver.resolveSymbol(type);
return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
{ __symbolic: 'class' };
};
return StaticReflector;
}());
/**
* @param {?} error
* @return {?}
*/
function expandedMessage(error) {
switch (error.message) {
case 'Reference to non-exported class':
if (error.context && error.context.className) {
return "Reference to a non-exported class " + error.context.className + ". Consider exporting the class";
}
break;
case 'Variable not initialized':
return 'Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler';
case 'Destructuring not supported':
return 'Referencing an exported destructured variable or constant is not supported by the template compiler. Consider simplifying this to avoid destructuring';
case 'Could not resolve type':
if (error.context && error.context.typeName) {
return "Could not resolve type " + error.context.typeName;
}
break;
case 'Function call not supported':
var /** @type {?} */ prefix = error.context && error.context.name ? "Calling function '" + error.context.name + "', f" : 'F';
return prefix +
'unction calls are not supported. Consider replacing the function or lambda with a reference to an exported function';
case 'Reference to a local symbol':
if (error.context && error.context.name) {
return "Reference to a local (non-exported) symbol '" + error.context.name + "'. Consider exporting the symbol";
}
break;
}
return error.message;
}
/**
* @param {?} error
* @return {?}
*/
function produceErrorMessage(error) {
return "Error encountered resolving symbol values statically. " + expandedMessage(error);
}
/**
* @param {?} input
* @param {?} transform
* @return {?}
*/
function mapStringMap(input, transform) {
if (!input)
return {};
var /** @type {?} */ result = {};
Object.keys(input).forEach(function (key) {
var /** @type {?} */ value = transform(input[key], key);
if (!shouldIgnore(value)) {
if (HIDDEN_KEY.test(key)) {
Object.defineProperty(result, key, { enumerable: false, configurable: true, value: value });
}
else {
result[key] = value;
}
}
});
return result;
}
/**
* @param {?} o
* @return {?}
*/
function isPrimitive(o) {
return o === null || (typeof o !== 'function' && typeof o !== 'object');
}
/**
* @abstract
*/
var BindingScope = (function () {
function BindingScope() {
}
/**
* @abstract
* @param {?} name
* @return {?}
*/
BindingScope.prototype.resolve = function (name) { };
/**
* @return {?}
*/
BindingScope.build = function () {
var /** @type {?} */ current = new Map();
return {
define: function (name, value) {
current.set(name, value);
return this;
},
done: function () {
return current.size > 0 ? new PopulatedScope(current) : BindingScope.empty;
}
};
};
return BindingScope;
}());
BindingScope.missing = {};
BindingScope.empty = { resolve: function (name) { return BindingScope.missing; } };
var PopulatedScope = (function (_super) {
__extends(PopulatedScope, _super);
/**
* @param {?} bindings
*/
function PopulatedScope(bindings) {
var _this = _super.call(this) || this;
_this.bindings = bindings;
return _this;
}
/**
* @param {?} name
* @return {?}
*/
PopulatedScope.prototype.resolve = function (name) {
return this.bindings.has(name) ? this.bindings.get(name) : BindingScope.missing;
};
return PopulatedScope;
}(BindingScope));
/**
* @param {?} message
* @param {?} fileName
* @param {?} line
* @param {?} column
* @return {?}
*/
function positionalError(message, fileName, line, column) {
var /** @type {?} */ result = new Error(message);
((result)).fileName = fileName;
((result)).line = line;
((result)).column = column;
return result;
}
/**
* @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
*/
var ResolvedStaticSymbol = (function () {
/**
* @param {?} symbol
* @param {?} metadata
*/
function ResolvedStaticSymbol(symbol, metadata) {
this.symbol = symbol;
this.metadata = metadata;
}
return ResolvedStaticSymbol;
}());
var SUPPORTED_SCHEMA_VERSION = 3;
/**
* This class is responsible for loading metadata per symbol,
* and normalizing references between symbols.
*
* Internally, it only uses symbols without members,
* and deduces the values for symbols with members based
* on these symbols.
*/
var StaticSymbolResolver = (function () {
/**
* @param {?} host
* @param {?} staticSymbolCache
* @param {?} summaryResolver
* @param {?=} errorRecorder
*/
function StaticSymbolResolver(host, staticSymbolCache, summaryResolver, errorRecorder) {
this.host = host;
this.staticSymbolCache = staticSymbolCache;
this.summaryResolver = summaryResolver;
this.errorRecorder = errorRecorder;
this.metadataCache = new Map();
this.resolvedSymbols = new Map();
this.resolvedFilePaths = new Set();
this.importAs = new Map();
this.symbolResourcePaths = new Map();
this.symbolFromFile = new Map();
}
/**
* @param {?} staticSymbol
* @return {?}
*/
StaticSymbolResolver.prototype.resolveSymbol = function (staticSymbol) {
if (staticSymbol.members.length > 0) {
return ((this._resolveSymbolMembers(staticSymbol)));
}
var /** @type {?} */ result = this.resolvedSymbols.get(staticSymbol);
if (result) {
return result;
}
result = ((this._resolveSymbolFromSummary(staticSymbol)));
if (result) {
return result;
}
// Note: Some users use libraries that were not compiled with ngc, i.e. they don't
// have summaries, only .d.ts files. So we always need to check both, the summary
// and metadata.
this._createSymbolsOf(staticSymbol.filePath);
result = ((this.resolvedSymbols.get(staticSymbol)));
return result;
};
/**
* getImportAs produces a symbol that can be used to import the given symbol.
* The import might be different than the symbol if the symbol is exported from
* a library with a summary; in which case we want to import the symbol from the
* ngfactory re-export instead of directly to avoid introducing a direct dependency
* on an otherwise indirect dependency.
*
* @param {?} staticSymbol the symbol for which to generate a import symbol
* @return {?}
*/
StaticSymbolResolver.prototype.getImportAs = function (staticSymbol) {
if (staticSymbol.members.length) {
var /** @type {?} */ baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name);
var /** @type {?} */ baseImportAs = this.getImportAs(baseSymbol);
return baseImportAs ?
this.getStaticSymbol(baseImportAs.filePath, baseImportAs.name, staticSymbol.members) :
null;
}
var /** @type {?} */ result = this.summaryResolver.getImportAs(staticSymbol);
if (!result) {
result = ((this.importAs.get(staticSymbol)));
}
return result;
};
/**
* getResourcePath produces the path to the original location of the symbol and should
* be used to determine the relative location of resource references recorded in
* symbol metadata.
* @param {?} staticSymbol
* @return {?}
*/
StaticSymbolResolver.prototype.getResourcePath = function (staticSymbol) {
return this.symbolResourcePaths.get(staticSymbol) || staticSymbol.filePath;
};
/**
* getTypeArity returns the number of generic type parameters the given symbol
* has. If the symbol is not a type the result is null.
* @param {?} staticSymbol
* @return {?}
*/
StaticSymbolResolver.prototype.getTypeArity = function (staticSymbol) {
// If the file is a factory file, don't resolve the symbol as doing so would
// cause the metadata for an factory file to be loaded which doesn't exist.
// All references to generated classes must include the correct arity whenever
// generating code.
if (isNgFactoryFile(staticSymbol.filePath)) {
return null;
}
var /** @type {?} */ resolvedSymbol = this.resolveSymbol(staticSymbol);
while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
resolvedSymbol = this.resolveSymbol(resolvedSymbol.metadata);
}
return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
};
/**
* @param {?} sourceSymbol
* @param {?} targetSymbol
* @return {?}
*/
StaticSymbolResolver.prototype.recordImportAs = function (sourceSymbol, targetSymbol) {
sourceSymbol.assertNoMembers();
targetSymbol.assertNoMembers();
this.importAs.set(sourceSymbol, targetSymbol);
};
/**
* Invalidate all information derived from the given file.
*
* @param {?} fileName the file to invalidate
* @return {?}
*/
StaticSymbolResolver.prototype.invalidateFile = function (fileName) {
this.metadataCache.delete(fileName);
this.resolvedFilePaths.delete(fileName);
var /** @type {?} */ symbols = this.symbolFromFile.get(fileName);
if (symbols) {
this.symbolFromFile.delete(fileName);
for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
var symbol = symbols_1[_i];
this.resolvedSymbols.delete(symbol);
this.importAs.delete(symbol);
this.symbolResourcePaths.delete(symbol);
}
}
};
/**
* @param {?} staticSymbol
* @return {?}
*/
StaticSymbolResolver.prototype._resolveSymbolMembers = function (staticSymbol) {
var /** @type {?} */ members = staticSymbol.members;
var /** @type {?} */ baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name));
if (!baseResolvedSymbol) {
return null;
}
var /** @type {?} */ baseMetadata = baseResolvedSymbol.metadata;
if (baseMetadata instanceof StaticSymbol) {
return new ResolvedStaticSymbol(staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
}
else if (baseMetadata && baseMetadata.__symbolic === 'class') {
if (baseMetadata.statics && members.length === 1) {
return new ResolvedStaticSymbol(staticSymbol, baseMetadata.statics[members[0]]);
}
}
else {
var /** @type {?} */ value = baseMetadata;
for (var /** @type {?} */ i = 0; i < members.length && value; i++) {
value = value[members[i]];
}
return new ResolvedStaticSymbol(staticSymbol, value);
}
return null;
};
/**
* @param {?} staticSymbol
* @return {?}
*/
StaticSymbolResolver.prototype._resolveSymbolFromSummary = function (staticSymbol) {
var /** @type {?} */ summary = this.summaryResolver.resolveSummary(staticSymbol);
return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null;
};
/**
* getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
* All types passed to the StaticResolver should be pseudo-types returned by this method.
*
* @param {?} declarationFile the absolute path of the file where the symbol is declared
* @param {?} name the name of the type.
* @param {?=} members a symbol for a static member of the named type
* @return {?}
*/
StaticSymbolResolver.prototype.getStaticSymbol = function (declarationFile, name, members) {
return this.staticSymbolCache.get(declarationFile, name, members);
};
/**
* @param {?} filePath
* @return {?}
*/
StaticSymbolResolver.prototype.getSymbolsOf = function (filePath) {
// Note: Some users use libraries that were not compiled with ngc, i.e. they don't
// have summaries, only .d.ts files. So we always need to check both, the summary
// and metadata.
var /** @type {?} */ symbols = new Set(this.summaryResolver.getSymbolsOf(filePath));
this._createSymbolsOf(filePath);
this.resolvedSymbols.forEach(function (resolvedSymbol) {
if (resolvedSymbol.symbol.filePath === filePath) {
symbols.add(resolvedSymbol.symbol);
}
});
return Array.from(symbols);
};
/**
* @param {?} filePath
* @return {?}
*/
StaticSymbolResolver.prototype._createSymbolsOf = function (filePath) {
var _this = this;
if (this.resolvedFilePaths.has(filePath)) {
return;
}
this.resolvedFilePaths.add(filePath);
var /** @type {?} */ resolvedSymbols = [];
var /** @type {?} */ metadata = this.getModuleMetadata(filePath);
if (metadata['metadata']) {
// handle direct declarations of the symbol
var /** @type {?} */ topLevelSymbolNames_1 = new Set(Object.keys(metadata['metadata']).map(unescapeIdentifier));
var /** @type {?} */ origins_1 = metadata['origins'] || {};
Object.keys(metadata['metadata']).forEach(function (metadataKey) {
var /** @type {?} */ symbolMeta = metadata['metadata'][metadataKey];
var /** @type {?} */ name = unescapeIdentifier(metadataKey);
var /** @type {?} */ symbol = _this.getStaticSymbol(filePath, name);
var /** @type {?} */ importSymbol = undefined;
if (metadata['importAs']) {
// Index bundle indexes should use the importAs module name instead of a reference
// to the .d.ts file directly.
importSymbol = _this.getStaticSymbol(metadata['importAs'], name);
_this.recordImportAs(symbol, importSymbol);
}
var /** @type {?} */ origin = origins_1.hasOwnProperty(metadataKey) && origins_1[metadataKey];
if (origin) {
// If the symbol is from a bundled index, use the declaration location of the
// symbol so relative references (such as './my.html') will be calculated
// correctly.
var /** @type {?} */ originFilePath = _this.resolveModule(origin, filePath);
if (!originFilePath) {
_this.reportError(new Error("Couldn't resolve original symbol for " + origin + " from " + filePath));
}
else {
_this.symbolResourcePaths.set(symbol, originFilePath);
}
}
resolvedSymbols.push(_this.createResolvedSymbol(symbol, filePath, topLevelSymbolNames_1, symbolMeta));
});
}
// handle the symbols in one of the re-export location
if (metadata['exports']) {
var _loop_1 = function (moduleExport) {
// handle the symbols in the list of explicitly re-exported symbols.
if (moduleExport.export) {
moduleExport.export.forEach(function (exportSymbol) {
var /** @type {?} */ symbolName;
if (typeof exportSymbol === 'string') {
symbolName = exportSymbol;
}
else {
symbolName = exportSymbol.as;
}
symbolName = unescapeIdentifier(symbolName);
var /** @type {?} */ symName = symbolName;
if (typeof exportSymbol !== 'string') {
symName = unescapeIdentifier(exportSymbol.name);
}
var /** @type {?} */ resolvedModule = _this.resolveModule(moduleExport.from, filePath);
if (resolvedModule) {
var /** @type {?} */ targetSymbol = _this.getStaticSymbol(resolvedModule, symName);
var /** @type {?} */ sourceSymbol = _this.getStaticSymbol(filePath, symbolName);
resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
}
});
}
else {
// handle the symbols via export * directives.
var /** @type {?} */ resolvedModule = this_1.resolveModule(moduleExport.from, filePath);
if (resolvedModule) {
var /** @type {?} */ nestedExports = this_1.getSymbolsOf(resolvedModule);
nestedExports.forEach(function (targetSymbol) {
var /** @type {?} */ sourceSymbol = _this.getStaticSymbol(filePath, targetSymbol.name);
resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
});
}
}
};
var this_1 = this;
for (var _i = 0, _a = metadata['exports']; _i < _a.length; _i++) {
var moduleExport = _a[_i];
_loop_1(/** @type {?} */ moduleExport);
}
}
resolvedSymbols.forEach(function (resolvedSymbol) { return _this.resolvedSymbols.set(resolvedSymbol.symbol, resolvedSymbol); });
this.symbolFromFile.set(filePath, resolvedSymbols.map(function (resolvedSymbol) { return resolvedSymbol.symbol; }));
};
/**
* @param {?} sourceSymbol
* @param {?} topLevelPath
* @param {?} topLevelSymbolNames
* @param {?} metadata
* @return {?}
*/
StaticSymbolResolver.prototype.createResolvedSymbol = function (sourceSymbol, topLevelPath, topLevelSymbolNames, metadata) {
// For classes that don't have Angular summaries / metadata,
// we only keep their arity, but nothing else
// (e.g. their constructor parameters).
// We do this to prevent introducing deep imports
// as we didn't generate .ngfactory.ts files with proper reexports.
if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && metadata &&
metadata['__symbolic'] === 'class') {
var /** @type {?} */ transformedMeta_1 = { __symbolic: 'class', arity: metadata.arity };
return new ResolvedStaticSymbol(sourceSymbol, transformedMeta_1);
}
var /** @type {?} */ self = this;
var ReferenceTransformer = (function (_super) {
__extends(ReferenceTransformer, _super);
function ReferenceTransformer() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} map
* @param {?} functionParams
* @return {?}
*/
ReferenceTransformer.prototype.visitStringMap = function (map, functionParams) {
var /** @type {?} */ symbolic = map['__symbolic'];
if (symbolic === 'function') {
var /** @type {?} */ oldLen = functionParams.length;
functionParams.push.apply(functionParams, (map['parameters'] || []));
var /** @type {?} */ result = _super.prototype.visitStringMap.call(this, map, functionParams);
functionParams.length = oldLen;
return result;
}
else if (symbolic === 'reference') {
var /** @type {?} */ module_1 = map['module'];
var /** @type {?} */ name = map['name'] ? unescapeIdentifier(map['name']) : map['name'];
if (!name) {
return null;
}
var /** @type {?} */ filePath = void 0;
if (module_1) {
filePath = ((self.resolveModule(module_1, sourceSymbol.filePath)));
if (!filePath) {
return {
__symbolic: 'error',
message: "Could not resolve " + module_1 + " relative to " + sourceSymbol.filePath + "."
};
}
return self.getStaticSymbol(filePath, name);
}
else if (functionParams.indexOf(name) >= 0) {
// reference to a function parameter
return { __symbolic: 'reference', name: name };
}
else {
if (topLevelSymbolNames.has(name)) {
return self.getStaticSymbol(topLevelPath, name);
}
// ambient value
null;
}
}
else {
return _super.prototype.visitStringMap.call(this, map, functionParams);
}
};
return ReferenceTransformer;
}(ValueTransformer));
var /** @type {?} */ transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
if (transformedMeta instanceof StaticSymbol) {
return this.createExport(sourceSymbol, transformedMeta);
}
return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
};
/**
* @param {?} sourceSymbol
* @param {?} targetSymbol
* @return {?}
*/
StaticSymbolResolver.prototype.createExport = function (sourceSymbol, targetSymbol) {
sourceSymbol.assertNoMembers();
targetSymbol.assertNoMembers();
if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath)) {
// This case is for an ng library importing symbols from a plain ts library
// transitively.
// Note: We rely on the fact that we discover symbols in the direction
// from source files to library files
this.importAs.set(targetSymbol, this.getImportAs(sourceSymbol) || sourceSymbol);
}
return new ResolvedStaticSymbol(sourceSymbol, targetSymbol);
};
/**
* @param {?} error
* @param {?=} context
* @param {?=} path
* @return {?}
*/
StaticSymbolResolver.prototype.reportError = function (error, context, path) {
if (this.errorRecorder) {
this.errorRecorder(error, (context && context.filePath) || path);
}
else {
throw error;
}
};
/**
* @param {?} module an absolute path to a module file.
* @return {?}
*/
StaticSymbolResolver.prototype.getModuleMetadata = function (module) {
var /** @type {?} */ moduleMetadata = this.metadataCache.get(module);
if (!moduleMetadata) {
var /** @type {?} */ moduleMetadatas = this.host.getMetadataFor(module);
if (moduleMetadatas) {
var /** @type {?} */ maxVersion_1 = -1;
moduleMetadatas.forEach(function (md) {
if (md['version'] > maxVersion_1) {
maxVersion_1 = md['version'];
moduleMetadata = md;
}
});
}
if (!moduleMetadata) {
moduleMetadata =
{ __symbolic: 'module', version: SUPPORTED_SCHEMA_VERSION, module: module, metadata: {} };
}
if (moduleMetadata['version'] != SUPPORTED_SCHEMA_VERSION) {
var /** @type {?} */ errorMessage = moduleMetadata['version'] == 2 ?
"Unsupported metadata version " + moduleMetadata['version'] + " for module " + module + ". This module should be compiled with a newer version of ngc" :
"Metadata version mismatch for module " + module + ", found version " + moduleMetadata['version'] + ", expected " + SUPPORTED_SCHEMA_VERSION;
this.reportError(new Error(errorMessage));
}
this.metadataCache.set(module, moduleMetadata);
}
return moduleMetadata;
};
/**
* @param {?} module
* @param {?} symbolName
* @param {?=} containingFile
* @return {?}
*/
StaticSymbolResolver.prototype.getSymbolByModule = function (module, symbolName, containingFile) {
var /** @type {?} */ filePath = this.resolveModule(module, containingFile);
if (!filePath) {
this.reportError(new Error("Could not resolve module " + module + (containingFile ? " relative to $ {\n containingFile\n } " : '')));
return this.getStaticSymbol("ERROR:" + module, symbolName);
}
return this.getStaticSymbol(filePath, symbolName);
};
/**
* @param {?} module
* @param {?=} containingFile
* @return {?}
*/
StaticSymbolResolver.prototype.resolveModule = function (module, containingFile) {
try {
return this.host.moduleNameToFileName(module, containingFile);
}
catch (e) {
console.error("Could not resolve module '" + module + "' relative to file " + containingFile);
this.reportError(e, undefined, containingFile);
}
return null;
};
return StaticSymbolResolver;
}());
/**
* @param {?} identifier
* @return {?}
*/
function unescapeIdentifier(identifier) {
return identifier.startsWith('___') ? identifier.substr(1) : identifier;
}
/**
* @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
*/
var AotSummaryResolver = (function () {
/**
* @param {?} host
* @param {?} staticSymbolCache
*/
function AotSummaryResolver(host, staticSymbolCache) {
this.host = host;
this.staticSymbolCache = staticSymbolCache;
this.summaryCache = new Map();
this.loadedFilePaths = new Set();
this.importAs = new Map();
}
/**
* @param {?} filePath
* @return {?}
*/
AotSummaryResolver.prototype.isLibraryFile = function (filePath) {
// Note: We need to strip the .ngfactory. file path,
// so this method also works for generated files
// (for which host.isSourceFile will always return false).
return !this.host.isSourceFile(stripNgFactory(filePath));
};
/**
* @param {?} filePath
* @return {?}
*/
AotSummaryResolver.prototype.getLibraryFileName = function (filePath) { return this.host.getOutputFileName(filePath); };
/**
* @param {?} staticSymbol
* @return {?}
*/
AotSummaryResolver.prototype.resolveSummary = function (staticSymbol) {
staticSymbol.assertNoMembers();
var /** @type {?} */ summary = this.summaryCache.get(staticSymbol);
if (!summary) {
this._loadSummaryFile(staticSymbol.filePath);
summary = ((this.summaryCache.get(staticSymbol)));
}
return summary;
};
/**
* @param {?} filePath
* @return {?}
*/
AotSummaryResolver.prototype.getSymbolsOf = function (filePath) {
this._loadSummaryFile(filePath);
return Array.from(this.summaryCache.keys()).filter(function (symbol) { return symbol.filePath === filePath; });
};
/**
* @param {?} staticSymbol
* @return {?}
*/
AotSummaryResolver.prototype.getImportAs = function (staticSymbol) {
staticSymbol.assertNoMembers();
return ((this.importAs.get(staticSymbol)));
};
/**
* @param {?} filePath
* @return {?}
*/
AotSummaryResolver.prototype._loadSummaryFile = function (filePath) {
var _this = this;
if (this.loadedFilePaths.has(filePath)) {
return;
}
this.loadedFilePaths.add(filePath);
if (this.isLibraryFile(filePath)) {
var /** @type {?} */ summaryFilePath = summaryFileName(filePath);
var /** @type {?} */ json = void 0;
try {
json = this.host.loadSummary(summaryFilePath);
}
catch (e) {
console.error("Error loading summary file " + summaryFilePath);
throw e;
}
if (json) {
var _a = deserializeSummaries(this.staticSymbolCache, json), summaries = _a.summaries, importAs = _a.importAs;
summaries.forEach(function (summary) { return _this.summaryCache.set(summary.symbol, summary); });
importAs.forEach(function (importAs) {
_this.importAs.set(importAs.symbol, _this.staticSymbolCache.get(ngfactoryFilePath(filePath), importAs.importAs));
});
}
}
};
return AotSummaryResolver;
}());
/**
* @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
*/
/**
* Creates a new AotCompiler based on options and a host.
* @param {?} compilerHost
* @param {?} options
* @return {?}
*/
function createAotCompiler(compilerHost, options) {
var /** @type {?} */ translations = options.translations || '';
var /** @type {?} */ urlResolver = createOfflineCompileUrlResolver();
var /** @type {?} */ symbolCache = new StaticSymbolCache();
var /** @type {?} */ summaryResolver = new AotSummaryResolver(compilerHost, symbolCache);
var /** @type {?} */ symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver);
var /** @type {?} */ staticReflector = new StaticReflector(summaryResolver, symbolResolver);
StaticAndDynamicReflectionCapabilities.install(staticReflector);
var /** @type {?} */ console = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["_47" /* ɵConsole */]();
var /** @type {?} */ htmlParser = new I18NHtmlParser(new HtmlParser(), translations, options.i18nFormat, __WEBPACK_IMPORTED_MODULE_0__angular_core__["_19" /* MissingTranslationStrategy */].Warning, console);
var /** @type {?} */ config = new CompilerConfig({
defaultEncapsulation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].Emulated,
useJit: false,
enableLegacyTemplate: options.enableLegacyTemplate !== false,
});
var /** @type {?} */ normalizer = new DirectiveNormalizer({ get: function (url) { return compilerHost.loadResource(url); } }, urlResolver, htmlParser, config);
var /** @type {?} */ expressionParser = new Parser(new Lexer());
var /** @type {?} */ elementSchemaRegistry = new DomElementSchemaRegistry();
var /** @type {?} */ tmplParser = new TemplateParser(config, expressionParser, elementSchemaRegistry, htmlParser, console, []);
var /** @type {?} */ resolver = new CompileMetadataResolver(config, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector);
// TODO(vicb): do not pass options.i18nFormat here
var /** @type {?} */ importResolver = {
getImportAs: function (symbol) { return ((symbolResolver.getImportAs(symbol))); },
fileNameToModuleName: function (fileName, containingFilePath) { return compilerHost.fileNameToModuleName(fileName, containingFilePath); },
getTypeArity: function (symbol) { return ((symbolResolver.getTypeArity(symbol))); }
};
var /** @type {?} */ viewCompiler = new ViewCompiler(config, elementSchemaRegistry);
var /** @type {?} */ compiler = new AotCompiler(config, compilerHost, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, new NgModuleCompiler(), new TypeScriptEmitter(importResolver), summaryResolver, options.locale || null, options.i18nFormat || null, options.genFilePreamble || null, symbolResolver);
return { compiler: compiler, reflector: staticReflector };
}
/**
* @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
*/
/**
* @param {?} statements
* @param {?} resultVars
* @return {?}
*/
function interpretStatements(statements, resultVars) {
var /** @type {?} */ stmtsWithReturn = statements.concat([new ReturnStatement(literalArr(resultVars.map(function (resultVar) { return variable(resultVar); })))]);
var /** @type {?} */ ctx = new _ExecutionContext(null, null, null, new Map());
var /** @type {?} */ visitor = new StatementInterpreter();
var /** @type {?} */ result = visitor.visitAllStatements(stmtsWithReturn, ctx);
return result != null ? result.value : null;
}
/**
* @param {?} varNames
* @param {?} varValues
* @param {?} statements
* @param {?} ctx
* @param {?} visitor
* @return {?}
*/
function _executeFunctionStatements(varNames, varValues, statements, ctx, visitor) {
var /** @type {?} */ childCtx = ctx.createChildWihtLocalVars();
for (var /** @type {?} */ i = 0; i < varNames.length; i++) {
childCtx.vars.set(varNames[i], varValues[i]);
}
var /** @type {?} */ result = visitor.visitAllStatements(statements, childCtx);
return result ? result.value : null;
}
var _ExecutionContext = (function () {
/**
* @param {?} parent
* @param {?} instance
* @param {?} className
* @param {?} vars
*/
function _ExecutionContext(parent, instance, className, vars) {
this.parent = parent;
this.instance = instance;
this.className = className;
this.vars = vars;
}
/**
* @return {?}
*/
_ExecutionContext.prototype.createChildWihtLocalVars = function () {
return new _ExecutionContext(this, this.instance, this.className, new Map());
};
return _ExecutionContext;
}());
var ReturnValue = (function () {
/**
* @param {?} value
*/
function ReturnValue(value) {
this.value = value;
}
return ReturnValue;
}());
/**
* @param {?} _classStmt
* @param {?} _ctx
* @param {?} _visitor
* @return {?}
*/
function createDynamicClass(_classStmt, _ctx, _visitor) {
var /** @type {?} */ propertyDescriptors = {};
_classStmt.getters.forEach(function (getter) {
// Note: use `function` instead of arrow function to capture `this`
propertyDescriptors[getter.name] = {
configurable: false,
get: function () {
var /** @type {?} */ instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
}
};
});
_classStmt.methods.forEach(function (method) {
var /** @type {?} */ paramNames = method.params.map(function (param) { return param.name; });
// Note: use `function` instead of arrow function to capture `this`
propertyDescriptors[((method.name))] = {
writable: false,
configurable: false,
value: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var /** @type {?} */ instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
}
};
});
var /** @type {?} */ ctorParamNames = _classStmt.constructorMethod.params.map(function (param) { return param.name; });
// Note: use `function` instead of arrow function to capture `this`
var /** @type {?} */ ctor = function () {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var /** @type {?} */ instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
_classStmt.fields.forEach(function (field) { _this[field.name] = undefined; });
_executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
};
var /** @type {?} */ superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
return ctor;
}
var StatementInterpreter = (function () {
function StatementInterpreter() {
}
/**
* @param {?} ast
* @return {?}
*/
StatementInterpreter.prototype.debugAst = function (ast) { return debugOutputAstAsTypeScript(ast); };
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitDeclareVarStmt = function (stmt, ctx) {
ctx.vars.set(stmt.name, stmt.value.visitExpression(this, ctx));
return null;
};
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitWriteVarExpr = function (expr, ctx) {
var /** @type {?} */ value = expr.value.visitExpression(this, ctx);
var /** @type {?} */ currCtx = ctx;
while (currCtx != null) {
if (currCtx.vars.has(expr.name)) {
currCtx.vars.set(expr.name, value);
return value;
}
currCtx = ((currCtx.parent));
}
throw new Error("Not declared variable " + expr.name);
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitReadVarExpr = function (ast, ctx) {
var /** @type {?} */ varName = ((ast.name));
if (ast.builtin != null) {
switch (ast.builtin) {
case BuiltinVar.Super:
return ctx.instance.__proto__;
case BuiltinVar.This:
return ctx.instance;
case BuiltinVar.CatchError:
varName = CATCH_ERROR_VAR$2;
break;
case BuiltinVar.CatchStack:
varName = CATCH_STACK_VAR$2;
break;
default:
throw new Error("Unknown builtin variable " + ast.builtin);
}
}
var /** @type {?} */ currCtx = ctx;
while (currCtx != null) {
if (currCtx.vars.has(varName)) {
return currCtx.vars.get(varName);
}
currCtx = ((currCtx.parent));
}
throw new Error("Not declared variable " + varName);
};
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitWriteKeyExpr = function (expr, ctx) {
var /** @type {?} */ receiver = expr.receiver.visitExpression(this, ctx);
var /** @type {?} */ index = expr.index.visitExpression(this, ctx);
var /** @type {?} */ value = expr.value.visitExpression(this, ctx);
receiver[index] = value;
return value;
};
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitWritePropExpr = function (expr, ctx) {
var /** @type {?} */ receiver = expr.receiver.visitExpression(this, ctx);
var /** @type {?} */ value = expr.value.visitExpression(this, ctx);
receiver[expr.name] = value;
return value;
};
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitInvokeMethodExpr = function (expr, ctx) {
var /** @type {?} */ receiver = expr.receiver.visitExpression(this, ctx);
var /** @type {?} */ args = this.visitAllExpressions(expr.args, ctx);
var /** @type {?} */ result;
if (expr.builtin != null) {
switch (expr.builtin) {
case BuiltinMethod.ConcatArray:
result = receiver.concat.apply(receiver, args);
break;
case BuiltinMethod.SubscribeObservable:
result = receiver.subscribe({ next: args[0] });
break;
case BuiltinMethod.Bind:
result = receiver.bind.apply(receiver, args);
break;
default:
throw new Error("Unknown builtin method " + expr.builtin);
}
}
else {
result = receiver[((expr.name))].apply(receiver, args);
}
return result;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitInvokeFunctionExpr = function (stmt, ctx) {
var /** @type {?} */ args = this.visitAllExpressions(stmt.args, ctx);
var /** @type {?} */ fnExpr = stmt.fn;
if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
return null;
}
else {
var /** @type {?} */ fn$$1 = stmt.fn.visitExpression(this, ctx);
return fn$$1.apply(null, args);
}
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitReturnStmt = function (stmt, ctx) {
return new ReturnValue(stmt.value.visitExpression(this, ctx));
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitDeclareClassStmt = function (stmt, ctx) {
var /** @type {?} */ clazz = createDynamicClass(stmt, ctx, this);
ctx.vars.set(stmt.name, clazz);
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitExpressionStmt = function (stmt, ctx) {
return stmt.expr.visitExpression(this, ctx);
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitIfStmt = function (stmt, ctx) {
var /** @type {?} */ condition = stmt.condition.visitExpression(this, ctx);
if (condition) {
return this.visitAllStatements(stmt.trueCase, ctx);
}
else if (stmt.falseCase != null) {
return this.visitAllStatements(stmt.falseCase, ctx);
}
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitTryCatchStmt = function (stmt, ctx) {
try {
return this.visitAllStatements(stmt.bodyStmts, ctx);
}
catch (e) {
var /** @type {?} */ childCtx = ctx.createChildWihtLocalVars();
childCtx.vars.set(CATCH_ERROR_VAR$2, e);
childCtx.vars.set(CATCH_STACK_VAR$2, e.stack);
return this.visitAllStatements(stmt.catchStmts, childCtx);
}
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitThrowStmt = function (stmt, ctx) {
throw stmt.error.visitExpression(this, ctx);
};
/**
* @param {?} stmt
* @param {?=} context
* @return {?}
*/
StatementInterpreter.prototype.visitCommentStmt = function (stmt, context) { return null; };
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitInstantiateExpr = function (ast, ctx) {
var /** @type {?} */ args = this.visitAllExpressions(ast.args, ctx);
var /** @type {?} */ clazz = ast.classExpr.visitExpression(this, ctx);
return new (clazz.bind.apply(clazz, [void 0].concat(args)))();
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitLiteralExpr = function (ast, ctx) { return ast.value; };
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitExternalExpr = function (ast, ctx) {
return ast.value.reference;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitConditionalExpr = function (ast, ctx) {
if (ast.condition.visitExpression(this, ctx)) {
return ast.trueCase.visitExpression(this, ctx);
}
else if (ast.falseCase != null) {
return ast.falseCase.visitExpression(this, ctx);
}
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitNotExpr = function (ast, ctx) {
return !ast.condition.visitExpression(this, ctx);
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitCastExpr = function (ast, ctx) {
return ast.value.visitExpression(this, ctx);
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitFunctionExpr = function (ast, ctx) {
var /** @type {?} */ paramNames = ast.params.map(function (param) { return param.name; });
return _declareFn(paramNames, ast.statements, ctx, this);
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
var /** @type {?} */ paramNames = stmt.params.map(function (param) { return param.name; });
ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
var _this = this;
var /** @type {?} */ lhs = function () { return ast.lhs.visitExpression(_this, ctx); };
var /** @type {?} */ rhs = function () { return ast.rhs.visitExpression(_this, ctx); };
switch (ast.operator) {
case BinaryOperator.Equals:
return lhs() == rhs();
case BinaryOperator.Identical:
return lhs() === rhs();
case BinaryOperator.NotEquals:
return lhs() != rhs();
case BinaryOperator.NotIdentical:
return lhs() !== rhs();
case BinaryOperator.And:
return lhs() && rhs();
case BinaryOperator.Or:
return lhs() || rhs();
case BinaryOperator.Plus:
return lhs() + rhs();
case BinaryOperator.Minus:
return lhs() - rhs();
case BinaryOperator.Divide:
return lhs() / rhs();
case BinaryOperator.Multiply:
return lhs() * rhs();
case BinaryOperator.Modulo:
return lhs() % rhs();
case BinaryOperator.Lower:
return lhs() < rhs();
case BinaryOperator.LowerEquals:
return lhs() <= rhs();
case BinaryOperator.Bigger:
return lhs() > rhs();
case BinaryOperator.BiggerEquals:
return lhs() >= rhs();
default:
throw new Error("Unknown operator " + ast.operator);
}
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitReadPropExpr = function (ast, ctx) {
var /** @type {?} */ result;
var /** @type {?} */ receiver = ast.receiver.visitExpression(this, ctx);
result = receiver[ast.name];
return result;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitReadKeyExpr = function (ast, ctx) {
var /** @type {?} */ receiver = ast.receiver.visitExpression(this, ctx);
var /** @type {?} */ prop = ast.index.visitExpression(this, ctx);
return receiver[prop];
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitLiteralArrayExpr = function (ast, ctx) {
return this.visitAllExpressions(ast.entries, ctx);
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitLiteralMapExpr = function (ast, ctx) {
var _this = this;
var /** @type {?} */ result = {};
ast.entries.forEach(function (entry) { return ((result))[entry.key] = entry.value.visitExpression(_this, ctx); });
return result;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
StatementInterpreter.prototype.visitCommaExpr = function (ast, context) {
var /** @type {?} */ values = this.visitAllExpressions(ast.parts, context);
return values[values.length - 1];
};
/**
* @param {?} expressions
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitAllExpressions = function (expressions, ctx) {
var _this = this;
return expressions.map(function (expr) { return expr.visitExpression(_this, ctx); });
};
/**
* @param {?} statements
* @param {?} ctx
* @return {?}
*/
StatementInterpreter.prototype.visitAllStatements = function (statements, ctx) {
for (var /** @type {?} */ i = 0; i < statements.length; i++) {
var /** @type {?} */ stmt = statements[i];
var /** @type {?} */ val = stmt.visitStatement(this, ctx);
if (val instanceof ReturnValue) {
return val;
}
}
return null;
};
return StatementInterpreter;
}());
/**
* @param {?} varNames
* @param {?} statements
* @param {?} ctx
* @param {?} visitor
* @return {?}
*/
function _declareFn(varNames, statements, ctx, visitor) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return _executeFunctionStatements(varNames, args, statements, ctx, visitor);
};
}
var CATCH_ERROR_VAR$2 = 'error';
var CATCH_STACK_VAR$2 = 'stack';
/**
* @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
*/
/**
* @abstract
*/
var AbstractJsEmitterVisitor = (function (_super) {
__extends(AbstractJsEmitterVisitor, _super);
function AbstractJsEmitterVisitor() {
return _super.call(this, false) || this;
}
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
var _this = this;
ctx.pushClass(stmt);
this._visitClassConstructor(stmt, ctx);
if (stmt.parent != null) {
ctx.print(stmt, stmt.name + ".prototype = Object.create(");
stmt.parent.visitExpression(this, ctx);
ctx.println(stmt, ".prototype);");
}
stmt.getters.forEach(function (getter) { return _this._visitClassGetter(stmt, getter, ctx); });
stmt.methods.forEach(function (method) { return _this._visitClassMethod(stmt, method, ctx); });
ctx.popClass();
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
ctx.print(stmt, "function " + stmt.name + "(");
if (stmt.constructorMethod != null) {
this._visitParams(stmt.constructorMethod.params, ctx);
}
ctx.println(stmt, ") {");
ctx.incIndent();
if (stmt.constructorMethod != null) {
if (stmt.constructorMethod.body.length > 0) {
ctx.println(stmt, "var self = this;");
this.visitAllStatements(stmt.constructorMethod.body, ctx);
}
}
ctx.decIndent();
ctx.println(stmt, "}");
};
/**
* @param {?} stmt
* @param {?} getter
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype._visitClassGetter = function (stmt, getter, ctx) {
ctx.println(stmt, "Object.defineProperty(" + stmt.name + ".prototype, '" + getter.name + "', { get: function() {");
ctx.incIndent();
if (getter.body.length > 0) {
ctx.println(stmt, "var self = this;");
this.visitAllStatements(getter.body, ctx);
}
ctx.decIndent();
ctx.println(stmt, "}});");
};
/**
* @param {?} stmt
* @param {?} method
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype._visitClassMethod = function (stmt, method, ctx) {
ctx.print(stmt, stmt.name + ".prototype." + method.name + " = function(");
this._visitParams(method.params, ctx);
ctx.println(stmt, ") {");
ctx.incIndent();
if (method.body.length > 0) {
ctx.println(stmt, "var self = this;");
this.visitAllStatements(method.body, ctx);
}
ctx.decIndent();
ctx.println(stmt, "};");
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
if (ast.builtin === BuiltinVar.This) {
ctx.print(ast, 'self');
}
else if (ast.builtin === BuiltinVar.Super) {
throw new Error("'super' needs to be handled at a parent ast node, not at the variable level!");
}
else {
_super.prototype.visitReadVarExpr.call(this, ast, ctx);
}
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
ctx.print(stmt, "var " + stmt.name + " = ");
stmt.value.visitExpression(this, ctx);
ctx.println(stmt, ";");
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
ast.value.visitExpression(this, ctx);
return null;
};
/**
* @param {?} expr
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
var /** @type {?} */ fnExpr = expr.fn;
if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
((((ctx.currentClass)).parent)).visitExpression(this, ctx);
ctx.print(expr, ".call(this");
if (expr.args.length > 0) {
ctx.print(expr, ", ");
this.visitAllExpressions(expr.args, ctx, ',');
}
ctx.print(expr, ")");
}
else {
_super.prototype.visitInvokeFunctionExpr.call(this, expr, ctx);
}
return null;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
ctx.print(ast, "function(");
this._visitParams(ast.params, ctx);
ctx.println(ast, ") {");
ctx.incIndent();
this.visitAllStatements(ast.statements, ctx);
ctx.decIndent();
ctx.print(ast, "}");
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
ctx.print(stmt, "function " + stmt.name + "(");
this._visitParams(stmt.params, ctx);
ctx.println(stmt, ") {");
ctx.incIndent();
this.visitAllStatements(stmt.statements, ctx);
ctx.decIndent();
ctx.println(stmt, "}");
return null;
};
/**
* @param {?} stmt
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
ctx.println(stmt, "try {");
ctx.incIndent();
this.visitAllStatements(stmt.bodyStmts, ctx);
ctx.decIndent();
ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
ctx.incIndent();
var /** @type {?} */ catchStmts = [/** @type {?} */ (CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [
StmtModifier.Final
]))].concat(stmt.catchStmts);
this.visitAllStatements(catchStmts, ctx);
ctx.decIndent();
ctx.println(stmt, "}");
return null;
};
/**
* @param {?} params
* @param {?} ctx
* @return {?}
*/
AbstractJsEmitterVisitor.prototype._visitParams = function (params, ctx) {
this.visitAllObjects(function (param) { return ctx.print(null, param.name); }, params, ctx, ',');
};
/**
* @param {?} method
* @return {?}
*/
AbstractJsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
var /** @type {?} */ name;
switch (method) {
case BuiltinMethod.ConcatArray:
name = 'concat';
break;
case BuiltinMethod.SubscribeObservable:
name = 'subscribe';
break;
case BuiltinMethod.Bind:
name = 'bind';
break;
default:
throw new Error("Unknown builtin method: " + method);
}
return name;
};
return AbstractJsEmitterVisitor;
}(AbstractEmitterVisitor));
/**
* @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
*/
/**
* @param {?} sourceUrl
* @param {?} ctx
* @param {?} vars
* @return {?}
*/
function evalExpression(sourceUrl$$1, ctx, vars) {
var /** @type {?} */ fnBody = ctx.toSource() + "\n//# sourceURL=" + sourceUrl$$1;
var /** @type {?} */ fnArgNames = [];
var /** @type {?} */ fnArgValues = [];
for (var /** @type {?} */ argName in vars) {
fnArgNames.push(argName);
fnArgValues.push(vars[argName]);
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["E" /* isDevMode */])()) {
// using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
// E.g. ```
// function anonymous(a,b,c
// /**/) { ... }```
// We don't want to hard code this fact, so we auto detect it via an empty function first.
var /** @type {?} */ emptyFn = new (Function.bind.apply(Function, [void 0].concat(fnArgNames.concat('return null;'))))().toString();
var /** @type {?} */ headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl$$1, sourceUrl$$1, headerLines).toJsComment();
}
return new (Function.bind.apply(Function, [void 0].concat(fnArgNames.concat(fnBody))))().apply(void 0, fnArgValues);
}
/**
* @param {?} sourceUrl
* @param {?} statements
* @param {?} resultVars
* @return {?}
*/
function jitStatements(sourceUrl$$1, statements, resultVars) {
var /** @type {?} */ converter = new JitEmitterVisitor();
var /** @type {?} */ ctx = EmitterVisitorContext.createRoot(resultVars);
var /** @type {?} */ returnStmt = new ReturnStatement(literalArr(resultVars.map(function (resultVar) { return variable(resultVar); })));
converter.visitAllStatements(statements.concat([returnStmt]), ctx);
return evalExpression(sourceUrl$$1, ctx, converter.getArgs());
}
var JitEmitterVisitor = (function (_super) {
__extends(JitEmitterVisitor, _super);
function JitEmitterVisitor() {
var _this = _super.apply(this, arguments) || this;
_this._evalArgNames = [];
_this._evalArgValues = [];
return _this;
}
/**
* @return {?}
*/
JitEmitterVisitor.prototype.getArgs = function () {
var /** @type {?} */ result = {};
for (var /** @type {?} */ i = 0; i < this._evalArgNames.length; i++) {
result[this._evalArgNames[i]] = this._evalArgValues[i];
}
return result;
};
/**
* @param {?} ast
* @param {?} ctx
* @return {?}
*/
JitEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
var /** @type {?} */ value = ast.value.reference;
var /** @type {?} */ id = this._evalArgValues.indexOf(value);
if (id === -1) {
id = this._evalArgValues.length;
this._evalArgValues.push(value);
var /** @type {?} */ name = identifierName(ast.value) || 'val';
this._evalArgNames.push("jit_" + name + id);
}
ctx.print(ast, this._evalArgNames[id]);
return null;
};
return JitEmitterVisitor;
}(AbstractJsEmitterVisitor));
/**
* @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
*/
/**
* An internal module of the Angular compiler that begins with component types,
* extracts templates, and eventually produces a compiled version of the component
* ready for linking into an application.
*
* \@security When compiling templates at runtime, you must ensure that the entire template comes
* from a trusted source. Attacker-controlled data introduced by a template could expose your
* application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
*/
var JitCompiler = (function () {
/**
* @param {?} _injector
* @param {?} _metadataResolver
* @param {?} _templateParser
* @param {?} _styleCompiler
* @param {?} _viewCompiler
* @param {?} _ngModuleCompiler
* @param {?} _compilerConfig
* @param {?} _console
*/
function JitCompiler(_injector, _metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _ngModuleCompiler, _compilerConfig, _console) {
this._injector = _injector;
this._metadataResolver = _metadataResolver;
this._templateParser = _templateParser;
this._styleCompiler = _styleCompiler;
this._viewCompiler = _viewCompiler;
this._ngModuleCompiler = _ngModuleCompiler;
this._compilerConfig = _compilerConfig;
this._console = _console;
this._compiledTemplateCache = new Map();
this._compiledHostTemplateCache = new Map();
this._compiledDirectiveWrapperCache = new Map();
this._compiledNgModuleCache = new Map();
this._sharedStylesheetCount = 0;
}
Object.defineProperty(JitCompiler.prototype, "injector", {
/**
* @return {?}
*/
get: function () { return this._injector; },
enumerable: true,
configurable: true
});
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
JitCompiler.prototype.compileModuleSync = function (moduleType) {
return ((this._compileModuleAndComponents(moduleType, true).syncResult));
};
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
JitCompiler.prototype.compileModuleAsync = function (moduleType) {
return ((this._compileModuleAndComponents(moduleType, false).asyncResult));
};
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
JitCompiler.prototype.compileModuleAndAllComponentsSync = function (moduleType) {
return ((this._compileModuleAndAllComponents(moduleType, true).syncResult));
};
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
JitCompiler.prototype.compileModuleAndAllComponentsAsync = function (moduleType) {
return ((this._compileModuleAndAllComponents(moduleType, false).asyncResult));
};
/**
* @param {?} component
* @return {?}
*/
JitCompiler.prototype.getNgContentSelectors = function (component) {
this._console.warn('Compiler.getNgContentSelectors is deprecated. Use ComponentFactory.ngContentSelectors instead!');
var /** @type {?} */ template = this._compiledTemplateCache.get(component);
if (!template) {
throw new Error("The component " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(component) + " is not yet compiled!");
}
return ((template.compMeta.template)).ngContentSelectors;
};
/**
* @template T
* @param {?} moduleType
* @param {?} isSync
* @return {?}
*/
JitCompiler.prototype._compileModuleAndComponents = function (moduleType, isSync) {
var _this = this;
var /** @type {?} */ loadingPromise = this._loadModules(moduleType, isSync);
var /** @type {?} */ createResult = function () {
_this._compileComponents(moduleType, null);
return _this._compileModule(moduleType);
};
if (isSync) {
return new SyncAsyncResult(createResult());
}
else {
return new SyncAsyncResult(null, loadingPromise.then(createResult));
}
};
/**
* @template T
* @param {?} moduleType
* @param {?} isSync
* @return {?}
*/
JitCompiler.prototype._compileModuleAndAllComponents = function (moduleType, isSync) {
var _this = this;
var /** @type {?} */ loadingPromise = this._loadModules(moduleType, isSync);
var /** @type {?} */ createResult = function () {
var /** @type {?} */ componentFactories = [];
_this._compileComponents(moduleType, componentFactories);
return new __WEBPACK_IMPORTED_MODULE_0__angular_core__["_70" /* ModuleWithComponentFactories */](_this._compileModule(moduleType), componentFactories);
};
if (isSync) {
return new SyncAsyncResult(createResult());
}
else {
return new SyncAsyncResult(null, loadingPromise.then(createResult));
}
};
/**
* @param {?} mainModule
* @param {?} isSync
* @return {?}
*/
JitCompiler.prototype._loadModules = function (mainModule, isSync) {
var _this = this;
var /** @type {?} */ loadingPromises = [];
var /** @type {?} */ ngModule = ((this._metadataResolver.getNgModuleMetadata(mainModule)));
// Note: the loadingPromise for a module only includes the loading of the exported directives
// of imported modules.
// However, for runtime compilation, we want to transitively compile all modules,
// so we also need to call loadNgModuleDirectiveAndPipeMetadata for all nested modules.
ngModule.transitiveModule.modules.forEach(function (localModuleMeta) {
loadingPromises.push(_this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(localModuleMeta.reference, isSync));
});
return Promise.all(loadingPromises);
};
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
JitCompiler.prototype._compileModule = function (moduleType) {
var _this = this;
var /** @type {?} */ ngModuleFactory = ((this._compiledNgModuleCache.get(moduleType)));
if (!ngModuleFactory) {
var /** @type {?} */ moduleMeta_1 = ((this._metadataResolver.getNgModuleMetadata(moduleType)));
// Always provide a bound Compiler
var /** @type {?} */ extraProviders = [this._metadataResolver.getProviderMetadata(new ProviderMeta(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_11" /* Compiler */], { useFactory: function () { return new ModuleBoundCompiler(_this, moduleMeta_1.type.reference); } }))];
var /** @type {?} */ compileResult = this._ngModuleCompiler.compile(moduleMeta_1, extraProviders);
if (!this._compilerConfig.useJit) {
ngModuleFactory =
interpretStatements(compileResult.statements, [compileResult.ngModuleFactoryVar])[0];
}
else {
ngModuleFactory = jitStatements(ngModuleJitUrl(moduleMeta_1), compileResult.statements, [compileResult.ngModuleFactoryVar])[0];
}
this._compiledNgModuleCache.set(moduleMeta_1.type.reference, ngModuleFactory);
}
return ngModuleFactory;
};
/**
* \@internal
* @param {?} mainModule
* @param {?} allComponentFactories
* @return {?}
*/
JitCompiler.prototype._compileComponents = function (mainModule, allComponentFactories) {
var _this = this;
var /** @type {?} */ ngModule = ((this._metadataResolver.getNgModuleMetadata(mainModule)));
var /** @type {?} */ moduleByDirective = new Map();
var /** @type {?} */ templates = new Set();
ngModule.transitiveModule.modules.forEach(function (localModuleSummary) {
var /** @type {?} */ localModuleMeta = ((_this._metadataResolver.getNgModuleMetadata(localModuleSummary.reference)));
localModuleMeta.declaredDirectives.forEach(function (dirIdentifier) {
moduleByDirective.set(dirIdentifier.reference, localModuleMeta);
var /** @type {?} */ dirMeta = _this._metadataResolver.getDirectiveMetadata(dirIdentifier.reference);
if (dirMeta.isComponent) {
templates.add(_this._createCompiledTemplate(dirMeta, localModuleMeta));
if (allComponentFactories) {
var /** @type {?} */ template = _this._createCompiledHostTemplate(dirMeta.type.reference, localModuleMeta);
templates.add(template);
allComponentFactories.push(/** @type {?} */ (dirMeta.componentFactory));
}
}
});
});
ngModule.transitiveModule.modules.forEach(function (localModuleSummary) {
var /** @type {?} */ localModuleMeta = ((_this._metadataResolver.getNgModuleMetadata(localModuleSummary.reference)));
localModuleMeta.declaredDirectives.forEach(function (dirIdentifier) {
var /** @type {?} */ dirMeta = _this._metadataResolver.getDirectiveMetadata(dirIdentifier.reference);
if (dirMeta.isComponent) {
dirMeta.entryComponents.forEach(function (entryComponentType) {
var /** @type {?} */ moduleMeta = ((moduleByDirective.get(entryComponentType.componentType)));
templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
});
}
});
localModuleMeta.entryComponents.forEach(function (entryComponentType) {
var /** @type {?} */ moduleMeta = ((moduleByDirective.get(entryComponentType.componentType)));
templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
});
});
templates.forEach(function (template) { return _this._compileTemplate(template); });
};
/**
* @param {?} type
* @return {?}
*/
JitCompiler.prototype.clearCacheFor = function (type) {
this._compiledNgModuleCache.delete(type);
this._metadataResolver.clearCacheFor(type);
this._compiledHostTemplateCache.delete(type);
var /** @type {?} */ compiledTemplate = this._compiledTemplateCache.get(type);
if (compiledTemplate) {
this._compiledTemplateCache.delete(type);
}
};
/**
* @return {?}
*/
JitCompiler.prototype.clearCache = function () {
this._metadataResolver.clearCache();
this._compiledTemplateCache.clear();
this._compiledHostTemplateCache.clear();
this._compiledNgModuleCache.clear();
};
/**
* @param {?} compType
* @param {?} ngModule
* @return {?}
*/
JitCompiler.prototype._createCompiledHostTemplate = function (compType, ngModule) {
if (!ngModule) {
throw new Error("Component " + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["S" /* ɵstringify */])(compType) + " is not part of any NgModule or the module has not been imported into your module.");
}
var /** @type {?} */ compiledTemplate = this._compiledHostTemplateCache.get(compType);
if (!compiledTemplate) {
var /** @type {?} */ compMeta = this._metadataResolver.getDirectiveMetadata(compType);
assertComponent(compMeta);
var /** @type {?} */ componentFactory = (compMeta.componentFactory);
var /** @type {?} */ hostClass = this._metadataResolver.getHostComponentType(compType);
var /** @type {?} */ hostMeta = createHostComponentMeta(hostClass, compMeta, /** @type {?} */ (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_71" /* ɵgetComponentViewDefinitionFactory */])(componentFactory)));
compiledTemplate =
new CompiledTemplate(true, compMeta.type, hostMeta, ngModule, [compMeta.type]);
this._compiledHostTemplateCache.set(compType, compiledTemplate);
}
return compiledTemplate;
};
/**
* @param {?} compMeta
* @param {?} ngModule
* @return {?}
*/
JitCompiler.prototype._createCompiledTemplate = function (compMeta, ngModule) {
var /** @type {?} */ compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
if (!compiledTemplate) {
assertComponent(compMeta);
compiledTemplate = new CompiledTemplate(false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate);
}
return compiledTemplate;
};
/**
* @param {?} template
* @return {?}
*/
JitCompiler.prototype._compileTemplate = function (template) {
var _this = this;
if (template.isCompiled) {
return;
}
var /** @type {?} */ compMeta = template.compMeta;
var /** @type {?} */ externalStylesheetsByModuleUrl = new Map();
var /** @type {?} */ stylesCompileResult = this._styleCompiler.compileComponent(compMeta);
stylesCompileResult.externalStylesheets.forEach(function (r) { externalStylesheetsByModuleUrl.set(/** @type {?} */ ((r.meta.moduleUrl)), r); });
this._resolveStylesCompileResult(stylesCompileResult.componentStylesheet, externalStylesheetsByModuleUrl);
var /** @type {?} */ directives = template.directives.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
var /** @type {?} */ pipes = template.ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
var _a = this._templateParser.parse(compMeta, /** @type {?} */ ((((compMeta.template)).template)), directives, pipes, template.ngModule.schemas, templateSourceUrl(template.ngModule.type, template.compMeta, /** @type {?} */ ((template.compMeta.template)))), parsedTemplate = _a.template, usedPipes = _a.pipes;
var /** @type {?} */ compileResult = this._viewCompiler.compileComponent(compMeta, parsedTemplate, variable(stylesCompileResult.componentStylesheet.stylesVar), usedPipes);
var /** @type {?} */ statements = stylesCompileResult.componentStylesheet.statements.concat(compileResult.statements);
var /** @type {?} */ viewClassAndRendererTypeVars = compMeta.isHost ?
[compileResult.viewClassVar] :
[compileResult.viewClassVar, compileResult.rendererTypeVar];
var /** @type {?} */ viewClass;
var /** @type {?} */ rendererType;
if (!this._compilerConfig.useJit) {
_b = interpretStatements(statements, viewClassAndRendererTypeVars), viewClass = _b[0], rendererType = _b[1];
}
else {
_c = jitStatements(templateJitUrl(template.ngModule.type, template.compMeta), statements, viewClassAndRendererTypeVars), viewClass = _c[0], rendererType = _c[1];
}
template.compiled(viewClass, rendererType);
var _b, _c;
};
/**
* @param {?} result
* @param {?} externalStylesheetsByModuleUrl
* @return {?}
*/
JitCompiler.prototype._resolveStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
var _this = this;
result.dependencies.forEach(function (dep, i) {
var /** @type {?} */ nestedCompileResult = ((externalStylesheetsByModuleUrl.get(dep.moduleUrl)));
var /** @type {?} */ nestedStylesArr = _this._resolveAndEvalStylesCompileResult(nestedCompileResult, externalStylesheetsByModuleUrl);
dep.valuePlaceholder.reference = nestedStylesArr;
});
};
/**
* @param {?} result
* @param {?} externalStylesheetsByModuleUrl
* @return {?}
*/
JitCompiler.prototype._resolveAndEvalStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
this._resolveStylesCompileResult(result, externalStylesheetsByModuleUrl);
if (!this._compilerConfig.useJit) {
return interpretStatements(result.statements, [result.stylesVar])[0];
}
else {
return jitStatements(sharedStylesheetJitUrl(result.meta, this._sharedStylesheetCount++), result.statements, [result.stylesVar])[0];
}
};
return JitCompiler;
}());
JitCompiler.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
JitCompiler.ctorParameters = function () { return [
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Injector */], },
{ type: CompileMetadataResolver, },
{ type: TemplateParser, },
{ type: StyleCompiler, },
{ type: ViewCompiler, },
{ type: NgModuleCompiler, },
{ type: CompilerConfig, },
{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_47" /* ɵConsole */], },
]; };
var CompiledTemplate = (function () {
/**
* @param {?} isHost
* @param {?} compType
* @param {?} compMeta
* @param {?} ngModule
* @param {?} directives
*/
function CompiledTemplate(isHost, compType, compMeta, ngModule, directives) {
this.isHost = isHost;
this.compType = compType;
this.compMeta = compMeta;
this.ngModule = ngModule;
this.directives = directives;
this._viewClass = ((null));
this.isCompiled = false;
}
/**
* @param {?} viewClass
* @param {?} rendererType
* @return {?}
*/
CompiledTemplate.prototype.compiled = function (viewClass, rendererType) {
this._viewClass = viewClass;
((this.compMeta.componentViewType)).setDelegate(viewClass);
for (var /** @type {?} */ prop in rendererType) {
((this.compMeta.rendererType))[prop] = rendererType[prop];
}
this.isCompiled = true;
};
return CompiledTemplate;
}());
/**
* @param {?} meta
* @return {?}
*/
function assertComponent(meta) {
if (!meta.isComponent) {
throw new Error("Could not compile '" + identifierName(meta.type) + "' because it is not a component.");
}
}
/**
* Implements `Compiler` by delegating to the JitCompiler using a known module.
*/
var ModuleBoundCompiler = (function () {
/**
* @param {?} _delegate
* @param {?} _ngModule
*/
function ModuleBoundCompiler(_delegate, _ngModule) {
this._delegate = _delegate;
this._ngModule = _ngModule;
}
Object.defineProperty(ModuleBoundCompiler.prototype, "_injector", {
/**
* @return {?}
*/
get: function () { return this._delegate.injector; },
enumerable: true,
configurable: true
});
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
ModuleBoundCompiler.prototype.compileModuleSync = function (moduleType) {
return this._delegate.compileModuleSync(moduleType);
};
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
ModuleBoundCompiler.prototype.compileModuleAsync = function (moduleType) {
return this._delegate.compileModuleAsync(moduleType);
};
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
ModuleBoundCompiler.prototype.compileModuleAndAllComponentsSync = function (moduleType) {
return this._delegate.compileModuleAndAllComponentsSync(moduleType);
};
/**
* @template T
* @param {?} moduleType
* @return {?}
*/
ModuleBoundCompiler.prototype.compileModuleAndAllComponentsAsync = function (moduleType) {
return this._delegate.compileModuleAndAllComponentsAsync(moduleType);
};
/**
* @param {?} component
* @return {?}
*/
ModuleBoundCompiler.prototype.getNgContentSelectors = function (component) {
return this._delegate.getNgContentSelectors(component);
};
/**
* Clears all caches
* @return {?}
*/
ModuleBoundCompiler.prototype.clearCache = function () { this._delegate.clearCache(); };
/**
* Clears the cache for the given component/ngModule.
* @param {?} type
* @return {?}
*/
ModuleBoundCompiler.prototype.clearCacheFor = function (type) { this._delegate.clearCacheFor(type); };
return ModuleBoundCompiler;
}());
/**
* @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
*/
/**
* A container for message extracted from the templates.
*/
var MessageBundle = (function () {
/**
* @param {?} _htmlParser
* @param {?} _implicitTags
* @param {?} _implicitAttrs
* @param {?=} _locale
*/
function MessageBundle(_htmlParser, _implicitTags, _implicitAttrs, _locale) {
if (_locale === void 0) { _locale = null; }
this._htmlParser = _htmlParser;
this._implicitTags = _implicitTags;
this._implicitAttrs = _implicitAttrs;
this._locale = _locale;
this._messages = [];
}
/**
* @param {?} html
* @param {?} url
* @param {?} interpolationConfig
* @return {?}
*/
MessageBundle.prototype.updateFromTemplate = function (html, url, interpolationConfig) {
var /** @type {?} */ htmlParserResult = this._htmlParser.parse(html, url, true, interpolationConfig);
if (htmlParserResult.errors.length) {
return htmlParserResult.errors;
}
var /** @type {?} */ i18nParserResult = extractMessages(htmlParserResult.rootNodes, interpolationConfig, this._implicitTags, this._implicitAttrs);
if (i18nParserResult.errors.length) {
return i18nParserResult.errors;
}
(_a = this._messages).push.apply(_a, i18nParserResult.messages);
return null;
var _a;
};
/**
* @return {?}
*/
MessageBundle.prototype.getMessages = function () { return this._messages; };
/**
* @param {?} serializer
* @param {?=} filterSources
* @return {?}
*/
MessageBundle.prototype.write = function (serializer, filterSources) {
var /** @type {?} */ messages = {};
var /** @type {?} */ mapperVisitor = new MapPlaceholderNames();
// Deduplicate messages based on their ID
this._messages.forEach(function (message) {
var /** @type {?} */ id = serializer.digest(message);
if (!messages.hasOwnProperty(id)) {
messages[id] = message;
}
else {
(_a = messages[id].sources).push.apply(_a, message.sources);
}
var _a;
});
// Transform placeholder names using the serializer mapping
var /** @type {?} */ msgList = Object.keys(messages).map(function (id) {
var /** @type {?} */ mapper = serializer.createNameMapper(messages[id]);
var /** @type {?} */ src = messages[id];
var /** @type {?} */ nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
var /** @type {?} */ transformedMessage = new Message(nodes, {}, {}, src.meaning, src.description, id);
transformedMessage.sources = src.sources;
if (filterSources) {
transformedMessage.sources.forEach(function (source) { return source.filePath = filterSources(source.filePath); });
}
return transformedMessage;
});
return serializer.write(msgList, this._locale);
};
return MessageBundle;
}());
var MapPlaceholderNames = (function (_super) {
__extends(MapPlaceholderNames, _super);
function MapPlaceholderNames() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} nodes
* @param {?} mapper
* @return {?}
*/
MapPlaceholderNames.prototype.convert = function (nodes, mapper) {
var _this = this;
return mapper ? nodes.map(function (n) { return n.visit(_this, mapper); }) : nodes;
};
/**
* @param {?} ph
* @param {?} mapper
* @return {?}
*/
MapPlaceholderNames.prototype.visitTagPlaceholder = function (ph, mapper) {
var _this = this;
var /** @type {?} */ startName = ((mapper.toPublicName(ph.startName)));
var /** @type {?} */ closeName = ph.closeName ? ((mapper.toPublicName(ph.closeName))) : ph.closeName;
var /** @type {?} */ children = ph.children.map(function (n) { return n.visit(_this, mapper); });
return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan);
};
/**
* @param {?} ph
* @param {?} mapper
* @return {?}
*/
MapPlaceholderNames.prototype.visitPlaceholder = function (ph, mapper) {
return new Placeholder(ph.value, /** @type {?} */ ((mapper.toPublicName(ph.name))), ph.sourceSpan);
};
/**
* @param {?} ph
* @param {?} mapper
* @return {?}
*/
MapPlaceholderNames.prototype.visitIcuPlaceholder = function (ph, mapper) {
return new IcuPlaceholder(ph.value, /** @type {?} */ ((mapper.toPublicName(ph.name))), ph.sourceSpan);
};
return MapPlaceholderNames;
}(CloneVisitor));
/**
* @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
*/
/**
* Extract i18n messages from source code
*/
var Extractor = (function () {
/**
* @param {?} host
* @param {?} staticSymbolResolver
* @param {?} messageBundle
* @param {?} metadataResolver
*/
function Extractor(host, staticSymbolResolver, messageBundle, metadataResolver) {
this.host = host;
this.staticSymbolResolver = staticSymbolResolver;
this.messageBundle = messageBundle;
this.metadataResolver = metadataResolver;
}
/**
* @param {?} rootFiles
* @return {?}
*/
Extractor.prototype.extract = function (rootFiles) {
var _this = this;
var /** @type {?} */ programSymbols = extractProgramSymbols(this.staticSymbolResolver, rootFiles, this.host);
var _a = analyzeAndValidateNgModules(programSymbols, this.host, this.metadataResolver), files = _a.files, ngModules = _a.ngModules;
return Promise
.all(ngModules.map(function (ngModule) { return _this.metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
.then(function () {
var /** @type {?} */ errors = [];
files.forEach(function (file) {
var /** @type {?} */ compMetas = [];
file.directives.forEach(function (directiveType) {
var /** @type {?} */ dirMeta = _this.metadataResolver.getDirectiveMetadata(directiveType);
if (dirMeta && dirMeta.isComponent) {
compMetas.push(dirMeta);
}
});
compMetas.forEach(function (compMeta) {
var /** @type {?} */ html = ((((compMeta.template)).template));
var /** @type {?} */ interpolationConfig = InterpolationConfig.fromArray(/** @type {?} */ ((compMeta.template)).interpolation);
errors.push.apply(errors, ((_this.messageBundle.updateFromTemplate(html, file.srcUrl, interpolationConfig))));
});
});
if (errors.length) {
throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
}
return _this.messageBundle;
});
};
/**
* @param {?} host
* @param {?} locale
* @return {?}
*/
Extractor.create = function (host, locale) {
var /** @type {?} */ htmlParser = new I18NHtmlParser(new HtmlParser());
var /** @type {?} */ urlResolver = createOfflineCompileUrlResolver();
var /** @type {?} */ symbolCache = new StaticSymbolCache();
var /** @type {?} */ summaryResolver = new AotSummaryResolver(host, symbolCache);
var /** @type {?} */ staticSymbolResolver = new StaticSymbolResolver(host, symbolCache, summaryResolver);
var /** @type {?} */ staticReflector = new StaticReflector(summaryResolver, staticSymbolResolver);
StaticAndDynamicReflectionCapabilities.install(staticReflector);
var /** @type {?} */ config = new CompilerConfig({ defaultEncapsulation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].Emulated, useJit: false });
var /** @type {?} */ normalizer = new DirectiveNormalizer({ get: function (url) { return host.loadResource(url); } }, urlResolver, htmlParser, config);
var /** @type {?} */ elementSchemaRegistry = new DomElementSchemaRegistry();
var /** @type {?} */ resolver = new CompileMetadataResolver(config, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, new __WEBPACK_IMPORTED_MODULE_0__angular_core__["_47" /* ɵConsole */](), symbolCache, staticReflector);
// TODO(vicb): implicit tags & attributes
var /** @type {?} */ messageBundle = new MessageBundle(htmlParser, [], {}, locale);
var /** @type {?} */ extractor = new Extractor(host, staticSymbolResolver, messageBundle, resolver);
return { extractor: extractor, staticReflector: staticReflector };
};
return Extractor;
}());
/**
* @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
*/
/**
* @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
*/
var _NO_RESOURCE_LOADER = {
/**
* @param {?} url
* @return {?}
*/
get: function (url) {
throw new Error("No ResourceLoader implementation has been provided. Can't read the url \"" + url + "\"");
}
};
var baseHtmlParser = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["e" /* InjectionToken */]('HtmlParser');
/**
* @param {?} parser
* @param {?} translations
* @param {?} format
* @param {?} config
* @param {?} console
* @return {?}
*/
function i18nHtmlParserFactory(parser, translations, format, config, console) {
return new I18NHtmlParser(parser, translations, format, /** @type {?} */ ((config.missingTranslation)), console);
}
/**
* A set of providers that provide `JitCompiler` and its dependencies to use for
* template compilation.
*/
var COMPILER_PROVIDERS = [
{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_72" /* ɵReflector */], useValue: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */] },
{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_51" /* ɵReflectorReader */], useExisting: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_72" /* ɵReflector */] },
{ provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER },
SummaryResolver,
__WEBPACK_IMPORTED_MODULE_0__angular_core__["_47" /* ɵConsole */],
Lexer,
Parser,
{
provide: baseHtmlParser,
useClass: HtmlParser,
},
{
provide: I18NHtmlParser,
useFactory: i18nHtmlParserFactory,
deps: [
baseHtmlParser,
[new __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */](), new __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */](__WEBPACK_IMPORTED_MODULE_0__angular_core__["_73" /* TRANSLATIONS */])],
[new __WEBPACK_IMPORTED_MODULE_0__angular_core__["j" /* Optional */](), new __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */](__WEBPACK_IMPORTED_MODULE_0__angular_core__["_26" /* TRANSLATIONS_FORMAT */])],
[CompilerConfig],
[__WEBPACK_IMPORTED_MODULE_0__angular_core__["_47" /* ɵConsole */]],
]
},
{
provide: HtmlParser,
useExisting: I18NHtmlParser,
},
TemplateParser,
DirectiveNormalizer,
CompileMetadataResolver,
DEFAULT_PACKAGE_URL_PROVIDER,
StyleCompiler,
ViewCompiler,
NgModuleCompiler,
{ provide: CompilerConfig, useValue: new CompilerConfig() },
JitCompiler,
{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_11" /* Compiler */], useExisting: JitCompiler },
DomElementSchemaRegistry,
{ provide: ElementSchemaRegistry, useExisting: DomElementSchemaRegistry },
UrlResolver,
DirectiveResolver,
PipeResolver,
NgModuleResolver,
];
var JitCompilerFactory = (function () {
/**
* @param {?} defaultOptions
*/
function JitCompilerFactory(defaultOptions) {
var compilerOptions = {
useDebug: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["E" /* isDevMode */])(),
useJit: true,
defaultEncapsulation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["C" /* ViewEncapsulation */].Emulated,
missingTranslation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_19" /* MissingTranslationStrategy */].Warning,
enableLegacyTemplate: true,
};
this._defaultOptions = [compilerOptions].concat(defaultOptions);
}
/**
* @param {?=} options
* @return {?}
*/
JitCompilerFactory.prototype.createCompiler = function (options) {
if (options === void 0) { options = []; }
var /** @type {?} */ opts = _mergeOptions(this._defaultOptions.concat(options));
var /** @type {?} */ injector = __WEBPACK_IMPORTED_MODULE_0__angular_core__["_9" /* ReflectiveInjector */].resolveAndCreate([
COMPILER_PROVIDERS, {
provide: CompilerConfig,
useFactory: function () {
return new CompilerConfig({
// let explicit values from the compiler options overwrite options
// from the app providers
useJit: opts.useJit,
// let explicit values from the compiler options overwrite options
// from the app providers
defaultEncapsulation: opts.defaultEncapsulation,
missingTranslation: opts.missingTranslation,
enableLegacyTemplate: opts.enableLegacyTemplate,
});
},
deps: []
}, /** @type {?} */ ((opts.providers))
]);
return injector.get(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_11" /* Compiler */]);
};
return JitCompilerFactory;
}());
JitCompilerFactory.decorators = [
{ type: CompilerInjectable },
];
/**
* @nocollapse
*/
JitCompilerFactory.ctorParameters = function () { return [
{ type: Array, decorators: [{ type: __WEBPACK_IMPORTED_MODULE_0__angular_core__["k" /* Inject */], args: [__WEBPACK_IMPORTED_MODULE_0__angular_core__["_17" /* COMPILER_OPTIONS */],] },] },
]; };
/**
* @return {?}
*/
function _initReflector() {
__WEBPACK_IMPORTED_MODULE_0__angular_core__["_18" /* ɵreflector */].reflectionCapabilities = new __WEBPACK_IMPORTED_MODULE_0__angular_core__["_59" /* ɵReflectionCapabilities */]();
}
/**
* A platform that included corePlatform and the compiler.
*
* \@experimental
*/
var platformCoreDynamic = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["J" /* createPlatformFactory */])(__WEBPACK_IMPORTED_MODULE_0__angular_core__["K" /* platformCore */], 'coreDynamic', [
{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_17" /* COMPILER_OPTIONS */], useValue: {}, multi: true },
{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["_74" /* CompilerFactory */], useClass: JitCompilerFactory },
{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["H" /* PLATFORM_INITIALIZER */], useValue: _initReflector, multi: true },
]);
/**
* @param {?} optionsArr
* @return {?}
*/
function _mergeOptions(optionsArr) {
return {
useJit: _lastDefined(optionsArr.map(function (options) { return options.useJit; })),
defaultEncapsulation: _lastDefined(optionsArr.map(function (options) { return options.defaultEncapsulation; })),
providers: _mergeArrays(optionsArr.map(function (options) { return ((options.providers)); })),
missingTranslation: _lastDefined(optionsArr.map(function (options) { return options.missingTranslation; })),
};
}
/**
* @template T
* @param {?} args
* @return {?}
*/
function _lastDefined(args) {
for (var /** @type {?} */ i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}
/**
* @param {?} parts
* @return {?}
*/
function _mergeArrays(parts) {
var /** @type {?} */ result = [];
parts.forEach(function (part) { return part && result.push.apply(result, part); });
return result;
}
/**
* @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
*/
/**
* Interface that defines how import statements should be generated.
* @abstract
*/
var ImportResolver = (function () {
function ImportResolver() {
}
/**
* Converts a file path to a module name that can be used as an `import.
* I.e. `path/to/importedFile.ts` should be imported by `path/to/containingFile.ts`.
* @abstract
* @param {?} importedFilePath
* @param {?} containingFilePath
* @return {?}
*/
ImportResolver.prototype.fileNameToModuleName = function (importedFilePath, containingFilePath) { };
/**
* Converts the given StaticSymbol into another StaticSymbol that should be used
* to generate the import from.
* @abstract
* @param {?} symbol
* @return {?}
*/
ImportResolver.prototype.getImportAs = function (symbol) { };
/**
* Determine the arity of a type.
* @abstract
* @param {?} symbol
* @return {?}
*/
ImportResolver.prototype.getTypeArity = function (symbol) { };
return ImportResolver;
}());
/**
* @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
*/
/**
* @module
* @description
* Entry point for all APIs of the compiler package.
*
* <div class="callout is-critical">
* <header>Unstable APIs</header>
* <p>
* All compiler apis are currently considered experimental and private!
* </p>
* <p>
* We expect the APIs in this package to keep on changing. Do not rely on them.
* </p>
* </div>
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the compiler package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
//# sourceMappingURL=compiler.js.map
//# sourceMappingURL=compiler.es5.js.map
/***/ }),
/* 129 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_compiler__ = __webpack_require__(128);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_common__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__angular_platform_browser__ = __webpack_require__(22);
/* unused harmony export RESOURCE_CACHE_PROVIDER */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return platformBrowserDynamic; });
/* unused harmony export VERSION */
/* unused harmony export ɵINTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS */
/* unused harmony export ɵResourceLoaderImpl */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.1
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @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
*/
var ResourceLoaderImpl = (function (_super) {
__extends(ResourceLoaderImpl, _super);
function ResourceLoaderImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourceLoaderImpl.prototype.get = function (url) {
var resolve;
var reject;
var promise = new Promise(function (res, rej) {
resolve = res;
reject = rej;
});
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'text';
xhr.onload = function () {
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in ResourceLoader Level2 spec (supported
// by IE10)
var response = xhr.response || xhr.responseText;
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = xhr.status === 1223 ? 204 : xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : 0;
}
if (200 <= status && status <= 300) {
resolve(response);
}
else {
reject("Failed to load " + url);
}
};
xhr.onerror = function () { reject("Failed to load " + url); };
xhr.send();
return promise;
};
return ResourceLoaderImpl;
}(__WEBPACK_IMPORTED_MODULE_0__angular_compiler__["a" /* ResourceLoader */]));
ResourceLoaderImpl.decorators = [
{ type: __WEBPACK_IMPORTED_MODULE_1__angular_core__["l" /* Injectable */] },
];
/** @nocollapse */
ResourceLoaderImpl.ctorParameters = function () { return []; };
/**
* @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
*/
var INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS = [
__WEBPACK_IMPORTED_MODULE_3__angular_platform_browser__["d" /* ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS */],
{
provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["_17" /* COMPILER_OPTIONS */],
useValue: { providers: [{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_compiler__["a" /* ResourceLoader */], useClass: ResourceLoaderImpl }] },
multi: true
},
{ provide: __WEBPACK_IMPORTED_MODULE_1__angular_core__["G" /* PLATFORM_ID */], useValue: __WEBPACK_IMPORTED_MODULE_2__angular_common__["b" /* ɵPLATFORM_BROWSER_ID */] },
];
/**
* @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
*/
/**
* An implementation of ResourceLoader that uses a template cache to avoid doing an actual
* ResourceLoader.
*
* The template cache needs to be built and loaded into window.$templateCache
* via a separate mechanism.
*/
var CachedResourceLoader = (function (_super) {
__extends(CachedResourceLoader, _super);
function CachedResourceLoader() {
var _this = _super.call(this) || this;
_this._cache = __WEBPACK_IMPORTED_MODULE_1__angular_core__["v" /* ɵglobal */].$templateCache;
if (_this._cache == null) {
throw new Error('CachedResourceLoader: Template cache was not found in $templateCache.');
}
return _this;
}
CachedResourceLoader.prototype.get = function (url) {
if (this._cache.hasOwnProperty(url)) {
return Promise.resolve(this._cache[url]);
}
else {
return Promise.reject('CachedResourceLoader: Did not find cached template for ' + url);
}
};
return CachedResourceLoader;
}(__WEBPACK_IMPORTED_MODULE_0__angular_compiler__["a" /* ResourceLoader */]));
/**
* @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
*/
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* @stable
*/
var VERSION = new __WEBPACK_IMPORTED_MODULE_1__angular_core__["u" /* Version */]('4.1.1');
/**
* @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
*/
/**
* @experimental
*/
var RESOURCE_CACHE_PROVIDER = [{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_compiler__["a" /* ResourceLoader */], useClass: CachedResourceLoader }];
/**
* @stable
*/
var platformBrowserDynamic = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["J" /* createPlatformFactory */])(__WEBPACK_IMPORTED_MODULE_0__angular_compiler__["b" /* platformCoreDynamic */], 'browserDynamic', INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS);
/**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the platform-browser-dynamic package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
//# sourceMappingURL=platform-browser-dynamic.es5.js.map
/***/ }),
/* 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 */,
/* 232 */,
/* 233 */,
/* 234 */,
/* 235 */,
/* 236 */,
/* 237 */,
/* 238 */,
/* 239 */,
/* 240 */,
/* 241 */,
/* 242 */,
/* 243 */,
/* 244 */,
/* 245 */,
/* 246 */,
/* 247 */,
/* 248 */,
/* 249 */,
/* 250 */,
/* 251 */,
/* 252 */,
/* 253 */,
/* 254 */,
/* 255 */,
/* 256 */,
/* 257 */,
/* 258 */,
/* 259 */,
/* 260 */,
/* 261 */,
/* 262 */,
/* 263 */,
/* 264 */,
/* 265 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var InnerSubscriber = (function (_super) {
__extends(InnerSubscriber, _super);
function InnerSubscriber(parent, outerValue, outerIndex) {
_super.call(this);
this.parent = parent;
this.outerValue = outerValue;
this.outerIndex = outerIndex;
this.index = 0;
}
InnerSubscriber.prototype._next = function (value) {
this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
};
InnerSubscriber.prototype._error = function (error) {
this.parent.notifyError(error, this);
this.unsubscribe();
};
InnerSubscriber.prototype._complete = function () {
this.parent.notifyComplete(this);
this.unsubscribe();
};
return InnerSubscriber;
}(Subscriber_1.Subscriber));
exports.InnerSubscriber = InnerSubscriber;
//# sourceMappingURL=InnerSubscriber.js.map
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* An execution context and a data structure to order tasks and schedule their
* execution. Provides a notion of (potentially virtual) time, through the
* `now()` getter method.
*
* Each unit of work in a Scheduler is called an {@link Action}.
*
* ```ts
* class Scheduler {
* now(): number;
* schedule(work, delay?, state?): Subscription;
* }
* ```
*
* @class Scheduler
*/
var Scheduler = (function () {
function Scheduler(SchedulerAction, now) {
if (now === void 0) { now = Scheduler.now; }
this.SchedulerAction = SchedulerAction;
this.now = now;
}
/**
* Schedules a function, `work`, for execution. May happen at some point in
* the future, according to the `delay` parameter, if specified. May be passed
* some context object, `state`, which will be passed to the `work` function.
*
* The given arguments will be processed an stored as an Action object in a
* queue of actions.
*
* @param {function(state: ?T): ?Subscription} work A function representing a
* task, or some unit of work to be executed by the Scheduler.
* @param {number} [delay] Time to wait before executing the work, where the
* time unit is implicit and defined by the Scheduler itself.
* @param {T} [state] Some contextual data that the `work` function uses when
* called by the Scheduler.
* @return {Subscription} A subscription in order to be able to unsubscribe
* the scheduled work.
*/
Scheduler.prototype.schedule = function (work, delay, state) {
if (delay === void 0) { delay = 0; }
return new this.SchedulerAction(this, work).schedule(state, delay);
};
Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
return Scheduler;
}());
exports.Scheduler = Scheduler;
//# sourceMappingURL=Scheduler.js.map
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscription_1 = __webpack_require__(26);
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var SubjectSubscription = (function (_super) {
__extends(SubjectSubscription, _super);
function SubjectSubscription(subject, subscriber) {
_super.call(this);
this.subject = subject;
this.subscriber = subscriber;
this.closed = false;
}
SubjectSubscription.prototype.unsubscribe = function () {
if (this.closed) {
return;
}
this.closed = true;
var subject = this.subject;
var observers = subject.observers;
this.subject = null;
if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
return;
}
var subscriberIndex = observers.indexOf(this.subscriber);
if (subscriberIndex !== -1) {
observers.splice(subscriberIndex, 1);
}
};
return SubjectSubscription;
}(Subscription_1.Subscription));
exports.SubjectSubscription = SubjectSubscription;
//# sourceMappingURL=SubjectSubscription.js.map
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var from_1 = __webpack_require__(107);
Observable_1.Observable.from = from_1.from;
//# sourceMappingURL=from.js.map
/***/ }),
/* 269 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var fromEvent_1 = __webpack_require__(297);
Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
//# sourceMappingURL=fromEvent.js.map
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var interval_1 = __webpack_require__(298);
Observable_1.Observable.interval = interval_1.interval;
//# sourceMappingURL=interval.js.map
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var merge_1 = __webpack_require__(109);
Observable_1.Observable.merge = merge_1.merge;
//# sourceMappingURL=merge.js.map
/***/ }),
/* 272 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var of_1 = __webpack_require__(110);
Observable_1.Observable.of = of_1.of;
//# sourceMappingURL=of.js.map
/***/ }),
/* 273 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var range_1 = __webpack_require__(299);
Observable_1.Observable.range = range_1.range;
//# sourceMappingURL=range.js.map
/***/ }),
/* 274 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var timer_1 = __webpack_require__(300);
Observable_1.Observable.timer = timer_1.timer;
//# sourceMappingURL=timer.js.map
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var bufferCount_1 = __webpack_require__(301);
Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
//# sourceMappingURL=bufferCount.js.map
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var bufferTime_1 = __webpack_require__(302);
Observable_1.Observable.prototype.bufferTime = bufferTime_1.bufferTime;
//# sourceMappingURL=bufferTime.js.map
/***/ }),
/* 277 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var debounceTime_1 = __webpack_require__(306);
Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
//# sourceMappingURL=debounceTime.js.map
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var delay_1 = __webpack_require__(307);
Observable_1.Observable.prototype.delay = delay_1.delay;
//# sourceMappingURL=delay.js.map
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var distinctUntilChanged_1 = __webpack_require__(308);
Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
//# sourceMappingURL=distinctUntilChanged.js.map
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var do_1 = __webpack_require__(309);
Observable_1.Observable.prototype.do = do_1._do;
Observable_1.Observable.prototype._do = do_1._do;
//# sourceMappingURL=do.js.map
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var filter_1 = __webpack_require__(111);
Observable_1.Observable.prototype.filter = filter_1.filter;
//# sourceMappingURL=filter.js.map
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var mergeMap_1 = __webpack_require__(78);
Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
//# sourceMappingURL=mergeMap.js.map
/***/ }),
/* 283 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var retry_1 = __webpack_require__(317);
Observable_1.Observable.prototype.retry = retry_1.retry;
//# sourceMappingURL=retry.js.map
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var retryWhen_1 = __webpack_require__(318);
Observable_1.Observable.prototype.retryWhen = retryWhen_1.retryWhen;
//# sourceMappingURL=retryWhen.js.map
/***/ }),
/* 285 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var switchMap_1 = __webpack_require__(320);
Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
//# sourceMappingURL=switchMap.js.map
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var take_1 = __webpack_require__(321);
Observable_1.Observable.prototype.take = take_1.take;
//# sourceMappingURL=take.js.map
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Observable_1 = __webpack_require__(0);
var ScalarObservable_1 = __webpack_require__(106);
var EmptyObservable_1 = __webpack_require__(46);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var ArrayLikeObservable = (function (_super) {
__extends(ArrayLikeObservable, _super);
function ArrayLikeObservable(arrayLike, scheduler) {
_super.call(this);
this.arrayLike = arrayLike;
this.scheduler = scheduler;
if (!scheduler && arrayLike.length === 1) {
this._isScalar = true;
this.value = arrayLike[0];
}
}
ArrayLikeObservable.create = function (arrayLike, scheduler) {
var length = arrayLike.length;
if (length === 0) {
return new EmptyObservable_1.EmptyObservable();
}
else if (length === 1) {
return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
}
else {
return new ArrayLikeObservable(arrayLike, scheduler);
}
};
ArrayLikeObservable.dispatch = function (state) {
var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
if (subscriber.closed) {
return;
}
if (index >= length) {
subscriber.complete();
return;
}
subscriber.next(arrayLike[index]);
state.index = index + 1;
this.schedule(state);
};
ArrayLikeObservable.prototype._subscribe = function (subscriber) {
var index = 0;
var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
var length = arrayLike.length;
if (scheduler) {
return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
});
}
else {
for (var i = 0; i < length && !subscriber.closed; i++) {
subscriber.next(arrayLike[i]);
}
subscriber.complete();
}
};
return ArrayLikeObservable;
}(Observable_1.Observable));
exports.ArrayLikeObservable = ArrayLikeObservable;
//# sourceMappingURL=ArrayLikeObservable.js.map
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subject_1 = __webpack_require__(25);
var Observable_1 = __webpack_require__(0);
var Subscriber_1 = __webpack_require__(5);
var Subscription_1 = __webpack_require__(26);
/**
* @class ConnectableObservable<T>
*/
var ConnectableObservable = (function (_super) {
__extends(ConnectableObservable, _super);
function ConnectableObservable(source, subjectFactory) {
_super.call(this);
this.source = source;
this.subjectFactory = subjectFactory;
this._refCount = 0;
}
ConnectableObservable.prototype._subscribe = function (subscriber) {
return this.getSubject().subscribe(subscriber);
};
ConnectableObservable.prototype.getSubject = function () {
var subject = this._subject;
if (!subject || subject.isStopped) {
this._subject = this.subjectFactory();
}
return this._subject;
};
ConnectableObservable.prototype.connect = function () {
var connection = this._connection;
if (!connection) {
connection = this._connection = new Subscription_1.Subscription();
connection.add(this.source
.subscribe(new ConnectableSubscriber(this.getSubject(), this)));
if (connection.closed) {
this._connection = null;
connection = Subscription_1.Subscription.EMPTY;
}
else {
this._connection = connection;
}
}
return connection;
};
ConnectableObservable.prototype.refCount = function () {
return this.lift(new RefCountOperator(this));
};
return ConnectableObservable;
}(Observable_1.Observable));
exports.ConnectableObservable = ConnectableObservable;
exports.connectableObservableDescriptor = {
operator: { value: null },
_refCount: { value: 0, writable: true },
_subject: { value: null, writable: true },
_connection: { value: null, writable: true },
_subscribe: { value: ConnectableObservable.prototype._subscribe },
getSubject: { value: ConnectableObservable.prototype.getSubject },
connect: { value: ConnectableObservable.prototype.connect },
refCount: { value: ConnectableObservable.prototype.refCount }
};
var ConnectableSubscriber = (function (_super) {
__extends(ConnectableSubscriber, _super);
function ConnectableSubscriber(destination, connectable) {
_super.call(this, destination);
this.connectable = connectable;
}
ConnectableSubscriber.prototype._error = function (err) {
this._unsubscribe();
_super.prototype._error.call(this, err);
};
ConnectableSubscriber.prototype._complete = function () {
this._unsubscribe();
_super.prototype._complete.call(this);
};
ConnectableSubscriber.prototype._unsubscribe = function () {
var connectable = this.connectable;
if (connectable) {
this.connectable = null;
var connection = connectable._connection;
connectable._refCount = 0;
connectable._subject = null;
connectable._connection = null;
if (connection) {
connection.unsubscribe();
}
}
};
return ConnectableSubscriber;
}(Subject_1.SubjectSubscriber));
var RefCountOperator = (function () {
function RefCountOperator(connectable) {
this.connectable = connectable;
}
RefCountOperator.prototype.call = function (subscriber, source) {
var connectable = this.connectable;
connectable._refCount++;
var refCounter = new RefCountSubscriber(subscriber, connectable);
var subscription = source.subscribe(refCounter);
if (!refCounter.closed) {
refCounter.connection = connectable.connect();
}
return subscription;
};
return RefCountOperator;
}());
var RefCountSubscriber = (function (_super) {
__extends(RefCountSubscriber, _super);
function RefCountSubscriber(destination, connectable) {
_super.call(this, destination);
this.connectable = connectable;
}
RefCountSubscriber.prototype._unsubscribe = function () {
var connectable = this.connectable;
if (!connectable) {
this.connection = null;
return;
}
this.connectable = null;
var refCount = connectable._refCount;
if (refCount <= 0) {
this.connection = null;
return;
}
connectable._refCount = refCount - 1;
if (refCount > 1) {
this.connection = null;
return;
}
///
// Compare the local RefCountSubscriber's connection Subscription to the
// connection Subscription on the shared ConnectableObservable. In cases
// where the ConnectableObservable source synchronously emits values, and
// the RefCountSubscriber's downstream Observers synchronously unsubscribe,
// execution continues to here before the RefCountOperator has a chance to
// supply the RefCountSubscriber with the shared connection Subscription.
// For example:
// ```
// Observable.range(0, 10)
// .publish()
// .refCount()
// .take(5)
// .subscribe();
// ```
// In order to account for this case, RefCountSubscriber should only dispose
// the ConnectableObservable's shared connection Subscription if the
// connection Subscription exists, *and* either:
// a. RefCountSubscriber doesn't have a reference to the shared connection
// Subscription yet, or,
// b. RefCountSubscriber's connection Subscription reference is identical
// to the shared connection Subscription
///
var connection = this.connection;
var sharedConnection = connectable._connection;
this.connection = null;
if (sharedConnection && (!connection || sharedConnection === connection)) {
sharedConnection.unsubscribe();
}
};
return RefCountSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=ConnectableObservable.js.map
/***/ }),
/* 289 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Observable_1 = __webpack_require__(0);
var EmptyObservable_1 = __webpack_require__(46);
var isArray_1 = __webpack_require__(47);
var subscribeToResult_1 = __webpack_require__(27);
var OuterSubscriber_1 = __webpack_require__(24);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var ForkJoinObservable = (function (_super) {
__extends(ForkJoinObservable, _super);
function ForkJoinObservable(sources, resultSelector) {
_super.call(this);
this.sources = sources;
this.resultSelector = resultSelector;
}
/* tslint:enable:max-line-length */
/**
* @param sources
* @return {any}
* @static true
* @name forkJoin
* @owner Observable
*/
ForkJoinObservable.create = function () {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i - 0] = arguments[_i];
}
if (sources === null || arguments.length === 0) {
return new EmptyObservable_1.EmptyObservable();
}
var resultSelector = null;
if (typeof sources[sources.length - 1] === 'function') {
resultSelector = sources.pop();
}
// if the first and only other argument besides the resultSelector is an array
// assume it's been called with `forkJoin([obs1, obs2, obs3], resultSelector)`
if (sources.length === 1 && isArray_1.isArray(sources[0])) {
sources = sources[0];
}
if (sources.length === 0) {
return new EmptyObservable_1.EmptyObservable();
}
return new ForkJoinObservable(sources, resultSelector);
};
ForkJoinObservable.prototype._subscribe = function (subscriber) {
return new ForkJoinSubscriber(subscriber, this.sources, this.resultSelector);
};
return ForkJoinObservable;
}(Observable_1.Observable));
exports.ForkJoinObservable = ForkJoinObservable;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var ForkJoinSubscriber = (function (_super) {
__extends(ForkJoinSubscriber, _super);
function ForkJoinSubscriber(destination, sources, resultSelector) {
_super.call(this, destination);
this.sources = sources;
this.resultSelector = resultSelector;
this.completed = 0;
this.haveValues = 0;
var len = sources.length;
this.total = len;
this.values = new Array(len);
for (var i = 0; i < len; i++) {
var source = sources[i];
var innerSubscription = subscribeToResult_1.subscribeToResult(this, source, null, i);
if (innerSubscription) {
innerSubscription.outerIndex = i;
this.add(innerSubscription);
}
}
}
ForkJoinSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.values[outerIndex] = innerValue;
if (!innerSub._hasValue) {
innerSub._hasValue = true;
this.haveValues++;
}
};
ForkJoinSubscriber.prototype.notifyComplete = function (innerSub) {
var destination = this.destination;
var _a = this, haveValues = _a.haveValues, resultSelector = _a.resultSelector, values = _a.values;
var len = values.length;
if (!innerSub._hasValue) {
destination.complete();
return;
}
this.completed++;
if (this.completed !== len) {
return;
}
if (haveValues === len) {
var value = resultSelector ? resultSelector.apply(this, values) : values;
destination.next(value);
}
destination.complete();
};
return ForkJoinSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
//# sourceMappingURL=ForkJoinObservable.js.map
/***/ }),
/* 290 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Observable_1 = __webpack_require__(0);
var tryCatch_1 = __webpack_require__(49);
var isFunction_1 = __webpack_require__(83);
var errorObject_1 = __webpack_require__(38);
var Subscription_1 = __webpack_require__(26);
var toString = Object.prototype.toString;
function isNodeStyleEventEmitter(sourceObj) {
return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
}
function isJQueryStyleEventEmitter(sourceObj) {
return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
}
function isNodeList(sourceObj) {
return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
}
function isHTMLCollection(sourceObj) {
return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
}
function isEventTarget(sourceObj) {
return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var FromEventObservable = (function (_super) {
__extends(FromEventObservable, _super);
function FromEventObservable(sourceObj, eventName, selector, options) {
_super.call(this);
this.sourceObj = sourceObj;
this.eventName = eventName;
this.selector = selector;
this.options = options;
}
/* tslint:enable:max-line-length */
/**
* Creates an Observable that emits events of a specific type coming from the
* given event target.
*
* <span class="informal">Creates an Observable from DOM events, or Node
* EventEmitter events or others.</span>
*
* <img src="./img/fromEvent.png" width="100%">
*
* Creates an Observable by attaching an event listener to an "event target",
* which may be an object with `addEventListener` and `removeEventListener`,
* a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the
* DOM, or an HTMLCollection from the DOM. The event handler is attached when
* the output Observable is subscribed, and removed when the Subscription is
* unsubscribed.
*
* @example <caption>Emits clicks happening on the DOM document</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* clicks.subscribe(x => console.log(x));
*
* // Results in:
* // MouseEvent object logged to console everytime a click
* // occurs on the document.
*
* @see {@link from}
* @see {@link fromEventPattern}
*
* @param {EventTargetLike} target The DOMElement, event target, Node.js
* EventEmitter, NodeList or HTMLCollection to attach the event handler to.
* @param {string} eventName The event name of interest, being emitted by the
* `target`.
* @param {EventListenerOptions} [options] Options to pass through to addEventListener
* @param {SelectorMethodSignature<T>} [selector] An optional function to
* post-process results. It takes the arguments from the event handler and
* should return a single value.
* @return {Observable<T>}
* @static true
* @name fromEvent
* @owner Observable
*/
FromEventObservable.create = function (target, eventName, options, selector) {
if (isFunction_1.isFunction(options)) {
selector = options;
options = undefined;
}
return new FromEventObservable(target, eventName, selector, options);
};
FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
var unsubscribe;
if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
for (var i = 0, len = sourceObj.length; i < len; i++) {
FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
}
}
else if (isEventTarget(sourceObj)) {
var source_1 = sourceObj;
sourceObj.addEventListener(eventName, handler, options);
unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
}
else if (isJQueryStyleEventEmitter(sourceObj)) {
var source_2 = sourceObj;
sourceObj.on(eventName, handler);
unsubscribe = function () { return source_2.off(eventName, handler); };
}
else if (isNodeStyleEventEmitter(sourceObj)) {
var source_3 = sourceObj;
sourceObj.addListener(eventName, handler);
unsubscribe = function () { return source_3.removeListener(eventName, handler); };
}
else {
throw new TypeError('Invalid event target');
}
subscriber.add(new Subscription_1.Subscription(unsubscribe));
};
FromEventObservable.prototype._subscribe = function (subscriber) {
var sourceObj = this.sourceObj;
var eventName = this.eventName;
var options = this.options;
var selector = this.selector;
var handler = selector ? function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
if (result === errorObject_1.errorObject) {
subscriber.error(errorObject_1.errorObject.e);
}
else {
subscriber.next(result);
}
} : function (e) { return subscriber.next(e); };
FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
};
return FromEventObservable;
}(Observable_1.Observable));
exports.FromEventObservable = FromEventObservable;
//# sourceMappingURL=FromEventObservable.js.map
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var isArray_1 = __webpack_require__(47);
var isArrayLike_1 = __webpack_require__(113);
var isPromise_1 = __webpack_require__(117);
var PromiseObservable_1 = __webpack_require__(105);
var IteratorObservable_1 = __webpack_require__(293);
var ArrayObservable_1 = __webpack_require__(75);
var ArrayLikeObservable_1 = __webpack_require__(287);
var iterator_1 = __webpack_require__(79);
var Observable_1 = __webpack_require__(0);
var observeOn_1 = __webpack_require__(315);
var observable_1 = __webpack_require__(80);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var FromObservable = (function (_super) {
__extends(FromObservable, _super);
function FromObservable(ish, scheduler) {
_super.call(this, null);
this.ish = ish;
this.scheduler = scheduler;
}
/**
* Creates an Observable from an Array, an array-like object, a Promise, an
* iterable object, or an Observable-like object.
*
* <span class="informal">Converts almost anything to an Observable.</span>
*
* <img src="./img/from.png" width="100%">
*
* Convert various other objects and data types into Observables. `from`
* converts a Promise or an array-like or an
* [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
* object into an Observable that emits the items in that promise or array or
* iterable. A String, in this context, is treated as an array of characters.
* Observable-like objects (contains a function named with the ES2015 Symbol
* for Observable) can also be converted through this operator.
*
* @example <caption>Converts an array to an Observable</caption>
* var array = [10, 20, 30];
* var result = Rx.Observable.from(array);
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // 10 20 30
*
* @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
* function* generateDoubles(seed) {
* var i = seed;
* while (true) {
* yield i;
* i = 2 * i; // double it
* }
* }
*
* var iterator = generateDoubles(3);
* var result = Rx.Observable.from(iterator).take(10);
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // 3 6 12 24 48 96 192 384 768 1536
*
* @see {@link create}
* @see {@link fromEvent}
* @see {@link fromEventPattern}
* @see {@link fromPromise}
*
* @param {ObservableInput<T>} ish A subscribable object, a Promise, an
* Observable-like, an Array, an iterable or an array-like object to be
* converted.
* @param {Scheduler} [scheduler] The scheduler on which to schedule the
* emissions of values.
* @return {Observable<T>} The Observable whose values are originally from the
* input object that was converted.
* @static true
* @name from
* @owner Observable
*/
FromObservable.create = function (ish, scheduler) {
if (ish != null) {
if (typeof ish[observable_1.observable] === 'function') {
if (ish instanceof Observable_1.Observable && !scheduler) {
return ish;
}
return new FromObservable(ish, scheduler);
}
else if (isArray_1.isArray(ish)) {
return new ArrayObservable_1.ArrayObservable(ish, scheduler);
}
else if (isPromise_1.isPromise(ish)) {
return new PromiseObservable_1.PromiseObservable(ish, scheduler);
}
else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') {
return new IteratorObservable_1.IteratorObservable(ish, scheduler);
}
else if (isArrayLike_1.isArrayLike(ish)) {
return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
}
}
throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
};
FromObservable.prototype._subscribe = function (subscriber) {
var ish = this.ish;
var scheduler = this.scheduler;
if (scheduler == null) {
return ish[observable_1.observable]().subscribe(subscriber);
}
else {
return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
}
};
return FromObservable;
}(Observable_1.Observable));
exports.FromObservable = FromObservable;
//# sourceMappingURL=FromObservable.js.map
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var isNumeric_1 = __webpack_require__(115);
var Observable_1 = __webpack_require__(0);
var async_1 = __webpack_require__(37);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var IntervalObservable = (function (_super) {
__extends(IntervalObservable, _super);
function IntervalObservable(period, scheduler) {
if (period === void 0) { period = 0; }
if (scheduler === void 0) { scheduler = async_1.async; }
_super.call(this);
this.period = period;
this.scheduler = scheduler;
if (!isNumeric_1.isNumeric(period) || period < 0) {
this.period = 0;
}
if (!scheduler || typeof scheduler.schedule !== 'function') {
this.scheduler = async_1.async;
}
}
/**
* Creates an Observable that emits sequential numbers every specified
* interval of time, on a specified IScheduler.
*
* <span class="informal">Emits incremental numbers periodically in time.
* </span>
*
* <img src="./img/interval.png" width="100%">
*
* `interval` returns an Observable that emits an infinite sequence of
* ascending integers, with a constant interval of time of your choosing
* between those emissions. The first emission is not sent immediately, but
* only after the first period has passed. By default, this operator uses the
* `async` IScheduler to provide a notion of time, but you may pass any
* IScheduler to it.
*
* @example <caption>Emits ascending numbers, one every second (1000ms)</caption>
* var numbers = Rx.Observable.interval(1000);
* numbers.subscribe(x => console.log(x));
*
* @see {@link timer}
* @see {@link delay}
*
* @param {number} [period=0] The interval size in milliseconds (by default)
* or the time unit determined by the scheduler's clock.
* @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
* the emission of values, and providing a notion of "time".
* @return {Observable} An Observable that emits a sequential number each time
* interval.
* @static true
* @name interval
* @owner Observable
*/
IntervalObservable.create = function (period, scheduler) {
if (period === void 0) { period = 0; }
if (scheduler === void 0) { scheduler = async_1.async; }
return new IntervalObservable(period, scheduler);
};
IntervalObservable.dispatch = function (state) {
var index = state.index, subscriber = state.subscriber, period = state.period;
subscriber.next(index);
if (subscriber.closed) {
return;
}
state.index += 1;
this.schedule(state, period);
};
IntervalObservable.prototype._subscribe = function (subscriber) {
var index = 0;
var period = this.period;
var scheduler = this.scheduler;
subscriber.add(scheduler.schedule(IntervalObservable.dispatch, period, {
index: index, subscriber: subscriber, period: period
}));
};
return IntervalObservable;
}(Observable_1.Observable));
exports.IntervalObservable = IntervalObservable;
//# sourceMappingURL=IntervalObservable.js.map
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var root_1 = __webpack_require__(16);
var Observable_1 = __webpack_require__(0);
var iterator_1 = __webpack_require__(79);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var IteratorObservable = (function (_super) {
__extends(IteratorObservable, _super);
function IteratorObservable(iterator, scheduler) {
_super.call(this);
this.scheduler = scheduler;
if (iterator == null) {
throw new Error('iterator cannot be null.');
}
this.iterator = getIterator(iterator);
}
IteratorObservable.create = function (iterator, scheduler) {
return new IteratorObservable(iterator, scheduler);
};
IteratorObservable.dispatch = function (state) {
var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
if (hasError) {
subscriber.error(state.error);
return;
}
var result = iterator.next();
if (result.done) {
subscriber.complete();
return;
}
subscriber.next(result.value);
state.index = index + 1;
if (subscriber.closed) {
if (typeof iterator.return === 'function') {
iterator.return();
}
return;
}
this.schedule(state);
};
IteratorObservable.prototype._subscribe = function (subscriber) {
var index = 0;
var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
if (scheduler) {
return scheduler.schedule(IteratorObservable.dispatch, 0, {
index: index, iterator: iterator, subscriber: subscriber
});
}
else {
do {
var result = iterator.next();
if (result.done) {
subscriber.complete();
break;
}
else {
subscriber.next(result.value);
}
if (subscriber.closed) {
if (typeof iterator.return === 'function') {
iterator.return();
}
break;
}
} while (true);
}
};
return IteratorObservable;
}(Observable_1.Observable));
exports.IteratorObservable = IteratorObservable;
var StringIterator = (function () {
function StringIterator(str, idx, len) {
if (idx === void 0) { idx = 0; }
if (len === void 0) { len = str.length; }
this.str = str;
this.idx = idx;
this.len = len;
}
StringIterator.prototype[iterator_1.iterator] = function () { return (this); };
StringIterator.prototype.next = function () {
return this.idx < this.len ? {
done: false,
value: this.str.charAt(this.idx++)
} : {
done: true,
value: undefined
};
};
return StringIterator;
}());
var ArrayIterator = (function () {
function ArrayIterator(arr, idx, len) {
if (idx === void 0) { idx = 0; }
if (len === void 0) { len = toLength(arr); }
this.arr = arr;
this.idx = idx;
this.len = len;
}
ArrayIterator.prototype[iterator_1.iterator] = function () { return this; };
ArrayIterator.prototype.next = function () {
return this.idx < this.len ? {
done: false,
value: this.arr[this.idx++]
} : {
done: true,
value: undefined
};
};
return ArrayIterator;
}());
function getIterator(obj) {
var i = obj[iterator_1.iterator];
if (!i && typeof obj === 'string') {
return new StringIterator(obj);
}
if (!i && obj.length !== undefined) {
return new ArrayIterator(obj);
}
if (!i) {
throw new TypeError('object is not iterable');
}
return obj[iterator_1.iterator]();
}
var maxSafeInteger = Math.pow(2, 53) - 1;
function toLength(o) {
var len = +o.length;
if (isNaN(len)) {
return 0;
}
if (len === 0 || !numberIsFinite(len)) {
return len;
}
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) {
return 0;
}
if (len > maxSafeInteger) {
return maxSafeInteger;
}
return len;
}
function numberIsFinite(value) {
return typeof value === 'number' && root_1.root.isFinite(value);
}
function sign(value) {
var valueAsNumber = +value;
if (valueAsNumber === 0) {
return valueAsNumber;
}
if (isNaN(valueAsNumber)) {
return valueAsNumber;
}
return valueAsNumber < 0 ? -1 : 1;
}
//# sourceMappingURL=IteratorObservable.js.map
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Observable_1 = __webpack_require__(0);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var RangeObservable = (function (_super) {
__extends(RangeObservable, _super);
function RangeObservable(start, count, scheduler) {
_super.call(this);
this.start = start;
this._count = count;
this.scheduler = scheduler;
}
/**
* Creates an Observable that emits a sequence of numbers within a specified
* range.
*
* <span class="informal">Emits a sequence of numbers in a range.</span>
*
* <img src="./img/range.png" width="100%">
*
* `range` operator emits a range of sequential integers, in order, where you
* select the `start` of the range and its `length`. By default, uses no
* IScheduler and just delivers the notifications synchronously, but may use
* an optional IScheduler to regulate those deliveries.
*
* @example <caption>Emits the numbers 1 to 10</caption>
* var numbers = Rx.Observable.range(1, 10);
* numbers.subscribe(x => console.log(x));
*
* @see {@link timer}
* @see {@link interval}
*
* @param {number} [start=0] The value of the first integer in the sequence.
* @param {number} [count=0] The number of sequential integers to generate.
* @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
* the emissions of the notifications.
* @return {Observable} An Observable of numbers that emits a finite range of
* sequential integers.
* @static true
* @name range
* @owner Observable
*/
RangeObservable.create = function (start, count, scheduler) {
if (start === void 0) { start = 0; }
if (count === void 0) { count = 0; }
return new RangeObservable(start, count, scheduler);
};
RangeObservable.dispatch = function (state) {
var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber;
if (index >= count) {
subscriber.complete();
return;
}
subscriber.next(start);
if (subscriber.closed) {
return;
}
state.index = index + 1;
state.start = start + 1;
this.schedule(state);
};
RangeObservable.prototype._subscribe = function (subscriber) {
var index = 0;
var start = this.start;
var count = this._count;
var scheduler = this.scheduler;
if (scheduler) {
return scheduler.schedule(RangeObservable.dispatch, 0, {
index: index, count: count, start: start, subscriber: subscriber
});
}
else {
do {
if (index++ >= count) {
subscriber.complete();
break;
}
subscriber.next(start++);
if (subscriber.closed) {
break;
}
} while (true);
}
};
return RangeObservable;
}(Observable_1.Observable));
exports.RangeObservable = RangeObservable;
//# sourceMappingURL=RangeObservable.js.map
/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var isNumeric_1 = __webpack_require__(115);
var Observable_1 = __webpack_require__(0);
var async_1 = __webpack_require__(37);
var isScheduler_1 = __webpack_require__(48);
var isDate_1 = __webpack_require__(114);
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
var TimerObservable = (function (_super) {
__extends(TimerObservable, _super);
function TimerObservable(dueTime, period, scheduler) {
if (dueTime === void 0) { dueTime = 0; }
_super.call(this);
this.period = -1;
this.dueTime = 0;
if (isNumeric_1.isNumeric(period)) {
this.period = Number(period) < 1 && 1 || Number(period);
}
else if (isScheduler_1.isScheduler(period)) {
scheduler = period;
}
if (!isScheduler_1.isScheduler(scheduler)) {
scheduler = async_1.async;
}
this.scheduler = scheduler;
this.dueTime = isDate_1.isDate(dueTime) ?
(+dueTime - this.scheduler.now()) :
dueTime;
}
/**
* Creates an Observable that starts emitting after an `initialDelay` and
* emits ever increasing numbers after each `period` of time thereafter.
*
* <span class="informal">Its like {@link interval}, but you can specify when
* should the emissions start.</span>
*
* <img src="./img/timer.png" width="100%">
*
* `timer` returns an Observable that emits an infinite sequence of ascending
* integers, with a constant interval of time, `period` of your choosing
* between those emissions. The first emission happens after the specified
* `initialDelay`. The initial delay may be a {@link Date}. By default, this
* operator uses the `async` IScheduler to provide a notion of time, but you
* may pass any IScheduler to it. If `period` is not specified, the output
* Observable emits only one value, `0`. Otherwise, it emits an infinite
* sequence.
*
* @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
* var numbers = Rx.Observable.timer(3000, 1000);
* numbers.subscribe(x => console.log(x));
*
* @example <caption>Emits one number after five seconds</caption>
* var numbers = Rx.Observable.timer(5000);
* numbers.subscribe(x => console.log(x));
*
* @see {@link interval}
* @see {@link delay}
*
* @param {number|Date} initialDelay The initial delay time to wait before
* emitting the first value of `0`.
* @param {number} [period] The period of time between emissions of the
* subsequent numbers.
* @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
* the emission of values, and providing a notion of "time".
* @return {Observable} An Observable that emits a `0` after the
* `initialDelay` and ever increasing numbers after each `period` of time
* thereafter.
* @static true
* @name timer
* @owner Observable
*/
TimerObservable.create = function (initialDelay, period, scheduler) {
if (initialDelay === void 0) { initialDelay = 0; }
return new TimerObservable(initialDelay, period, scheduler);
};
TimerObservable.dispatch = function (state) {
var index = state.index, period = state.period, subscriber = state.subscriber;
var action = this;
subscriber.next(index);
if (subscriber.closed) {
return;
}
else if (period === -1) {
return subscriber.complete();
}
state.index = index + 1;
action.schedule(state, period);
};
TimerObservable.prototype._subscribe = function (subscriber) {
var index = 0;
var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
return scheduler.schedule(TimerObservable.dispatch, dueTime, {
index: index, period: period, subscriber: subscriber
});
};
return TimerObservable;
}(Observable_1.Observable));
exports.TimerObservable = TimerObservable;
//# sourceMappingURL=TimerObservable.js.map
/***/ }),
/* 296 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ForkJoinObservable_1 = __webpack_require__(289);
exports.forkJoin = ForkJoinObservable_1.ForkJoinObservable.create;
//# sourceMappingURL=forkJoin.js.map
/***/ }),
/* 297 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var FromEventObservable_1 = __webpack_require__(290);
exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
//# sourceMappingURL=fromEvent.js.map
/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var IntervalObservable_1 = __webpack_require__(292);
exports.interval = IntervalObservable_1.IntervalObservable.create;
//# sourceMappingURL=interval.js.map
/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var RangeObservable_1 = __webpack_require__(294);
exports.range = RangeObservable_1.RangeObservable.create;
//# sourceMappingURL=range.js.map
/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var TimerObservable_1 = __webpack_require__(295);
exports.timer = TimerObservable_1.TimerObservable.create;
//# sourceMappingURL=timer.js.map
/***/ }),
/* 301 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/**
* Buffers the source Observable values until the size hits the maximum
* `bufferSize` given.
*
* <span class="informal">Collects values from the past as an array, and emits
* that array only when its size reaches `bufferSize`.</span>
*
* <img src="./img/bufferCount.png" width="100%">
*
* Buffers a number of values from the source Observable by `bufferSize` then
* emits the buffer and clears it, and starts a new buffer each
* `startBufferEvery` values. If `startBufferEvery` is not provided or is
* `null`, then new buffers are started immediately at the start of the source
* and when each buffer closes and is emitted.
*
* @example <caption>Emit the last two click events as an array</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var buffered = clicks.bufferCount(2);
* buffered.subscribe(x => console.log(x));
*
* @example <caption>On every click, emit the last two click events as an array</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var buffered = clicks.bufferCount(2, 1);
* buffered.subscribe(x => console.log(x));
*
* @see {@link buffer}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link pairwise}
* @see {@link windowCount}
*
* @param {number} bufferSize The maximum size of the buffer emitted.
* @param {number} [startBufferEvery] Interval at which to start a new buffer.
* For example if `startBufferEvery` is `2`, then a new buffer will be started
* on every other value from the source. A new buffer is started at the
* beginning of the source by default.
* @return {Observable<T[]>} An Observable of arrays of buffered values.
* @method bufferCount
* @owner Observable
*/
function bufferCount(bufferSize, startBufferEvery) {
if (startBufferEvery === void 0) { startBufferEvery = null; }
return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
}
exports.bufferCount = bufferCount;
var BufferCountOperator = (function () {
function BufferCountOperator(bufferSize, startBufferEvery) {
this.bufferSize = bufferSize;
this.startBufferEvery = startBufferEvery;
if (!startBufferEvery || bufferSize === startBufferEvery) {
this.subscriberClass = BufferCountSubscriber;
}
else {
this.subscriberClass = BufferSkipCountSubscriber;
}
}
BufferCountOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
};
return BufferCountOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var BufferCountSubscriber = (function (_super) {
__extends(BufferCountSubscriber, _super);
function BufferCountSubscriber(destination, bufferSize) {
_super.call(this, destination);
this.bufferSize = bufferSize;
this.buffer = [];
}
BufferCountSubscriber.prototype._next = function (value) {
var buffer = this.buffer;
buffer.push(value);
if (buffer.length == this.bufferSize) {
this.destination.next(buffer);
this.buffer = [];
}
};
BufferCountSubscriber.prototype._complete = function () {
var buffer = this.buffer;
if (buffer.length > 0) {
this.destination.next(buffer);
}
_super.prototype._complete.call(this);
};
return BufferCountSubscriber;
}(Subscriber_1.Subscriber));
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var BufferSkipCountSubscriber = (function (_super) {
__extends(BufferSkipCountSubscriber, _super);
function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
_super.call(this, destination);
this.bufferSize = bufferSize;
this.startBufferEvery = startBufferEvery;
this.buffers = [];
this.count = 0;
}
BufferSkipCountSubscriber.prototype._next = function (value) {
var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
this.count++;
if (count % startBufferEvery === 0) {
buffers.push([]);
}
for (var i = buffers.length; i--;) {
var buffer = buffers[i];
buffer.push(value);
if (buffer.length === bufferSize) {
buffers.splice(i, 1);
this.destination.next(buffer);
}
}
};
BufferSkipCountSubscriber.prototype._complete = function () {
var _a = this, buffers = _a.buffers, destination = _a.destination;
while (buffers.length > 0) {
var buffer = buffers.shift();
if (buffer.length > 0) {
destination.next(buffer);
}
}
_super.prototype._complete.call(this);
};
return BufferSkipCountSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=bufferCount.js.map
/***/ }),
/* 302 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var async_1 = __webpack_require__(37);
var Subscriber_1 = __webpack_require__(5);
var isScheduler_1 = __webpack_require__(48);
/* tslint:enable:max-line-length */
/**
* Buffers the source Observable values for a specific time period.
*
* <span class="informal">Collects values from the past as an array, and emits
* those arrays periodically in time.</span>
*
* <img src="./img/bufferTime.png" width="100%">
*
* Buffers values from the source for a specific time duration `bufferTimeSpan`.
* Unless the optional argument `bufferCreationInterval` is given, it emits and
* resets the buffer every `bufferTimeSpan` milliseconds. If
* `bufferCreationInterval` is given, this operator opens the buffer every
* `bufferCreationInterval` milliseconds and closes (emits and resets) the
* buffer every `bufferTimeSpan` milliseconds. When the optional argument
* `maxBufferSize` is specified, the buffer will be closed either after
* `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.
*
* @example <caption>Every second, emit an array of the recent click events</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var buffered = clicks.bufferTime(1000);
* buffered.subscribe(x => console.log(x));
*
* @example <caption>Every 5 seconds, emit the click events from the next 2 seconds</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var buffered = clicks.bufferTime(2000, 5000);
* buffered.subscribe(x => console.log(x));
*
* @see {@link buffer}
* @see {@link bufferCount}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link windowTime}
*
* @param {number} bufferTimeSpan The amount of time to fill each buffer array.
* @param {number} [bufferCreationInterval] The interval at which to start new
* buffers.
* @param {number} [maxBufferSize] The maximum buffer size.
* @param {Scheduler} [scheduler=async] The scheduler on which to schedule the
* intervals that determine buffer boundaries.
* @return {Observable<T[]>} An observable of arrays of buffered values.
* @method bufferTime
* @owner Observable
*/
function bufferTime(bufferTimeSpan) {
var length = arguments.length;
var scheduler = async_1.async;
if (isScheduler_1.isScheduler(arguments[arguments.length - 1])) {
scheduler = arguments[arguments.length - 1];
length--;
}
var bufferCreationInterval = null;
if (length >= 2) {
bufferCreationInterval = arguments[1];
}
var maxBufferSize = Number.POSITIVE_INFINITY;
if (length >= 3) {
maxBufferSize = arguments[2];
}
return this.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
}
exports.bufferTime = bufferTime;
var BufferTimeOperator = (function () {
function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
this.bufferTimeSpan = bufferTimeSpan;
this.bufferCreationInterval = bufferCreationInterval;
this.maxBufferSize = maxBufferSize;
this.scheduler = scheduler;
}
BufferTimeOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler));
};
return BufferTimeOperator;
}());
var Context = (function () {
function Context() {
this.buffer = [];
}
return Context;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var BufferTimeSubscriber = (function (_super) {
__extends(BufferTimeSubscriber, _super);
function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
_super.call(this, destination);
this.bufferTimeSpan = bufferTimeSpan;
this.bufferCreationInterval = bufferCreationInterval;
this.maxBufferSize = maxBufferSize;
this.scheduler = scheduler;
this.contexts = [];
var context = this.openContext();
this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
if (this.timespanOnly) {
var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan };
this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
}
else {
var closeState = { subscriber: this, context: context };
var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: this, scheduler: scheduler };
this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
}
}
BufferTimeSubscriber.prototype._next = function (value) {
var contexts = this.contexts;
var len = contexts.length;
var filledBufferContext;
for (var i = 0; i < len; i++) {
var context = contexts[i];
var buffer = context.buffer;
buffer.push(value);
if (buffer.length == this.maxBufferSize) {
filledBufferContext = context;
}
}
if (filledBufferContext) {
this.onBufferFull(filledBufferContext);
}
};
BufferTimeSubscriber.prototype._error = function (err) {
this.contexts.length = 0;
_super.prototype._error.call(this, err);
};
BufferTimeSubscriber.prototype._complete = function () {
var _a = this, contexts = _a.contexts, destination = _a.destination;
while (contexts.length > 0) {
var context = contexts.shift();
destination.next(context.buffer);
}
_super.prototype._complete.call(this);
};
BufferTimeSubscriber.prototype._unsubscribe = function () {
this.contexts = null;
};
BufferTimeSubscriber.prototype.onBufferFull = function (context) {
this.closeContext(context);
var closeAction = context.closeAction;
closeAction.unsubscribe();
this.remove(closeAction);
if (!this.closed && this.timespanOnly) {
context = this.openContext();
var bufferTimeSpan = this.bufferTimeSpan;
var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan };
this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
}
};
BufferTimeSubscriber.prototype.openContext = function () {
var context = new Context();
this.contexts.push(context);
return context;
};
BufferTimeSubscriber.prototype.closeContext = function (context) {
this.destination.next(context.buffer);
var contexts = this.contexts;
var spliceIndex = contexts ? contexts.indexOf(context) : -1;
if (spliceIndex >= 0) {
contexts.splice(contexts.indexOf(context), 1);
}
};
return BufferTimeSubscriber;
}(Subscriber_1.Subscriber));
function dispatchBufferTimeSpanOnly(state) {
var subscriber = state.subscriber;
var prevContext = state.context;
if (prevContext) {
subscriber.closeContext(prevContext);
}
if (!subscriber.closed) {
state.context = subscriber.openContext();
state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
}
}
function dispatchBufferCreation(state) {
var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler;
var context = subscriber.openContext();
var action = this;
if (!subscriber.closed) {
subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context }));
action.schedule(state, bufferCreationInterval);
}
}
function dispatchBufferClose(arg) {
var subscriber = arg.subscriber, context = arg.context;
subscriber.closeContext(context);
}
//# sourceMappingURL=bufferTime.js.map
/***/ }),
/* 303 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var OuterSubscriber_1 = __webpack_require__(24);
var subscribeToResult_1 = __webpack_require__(27);
/**
* Catches errors on the observable to be handled by returning a new observable or throwing an error.
*
* <img src="./img/catch.png" width="100%">
*
* @example <caption>Continues with a different Observable when there's an error</caption>
*
* Observable.of(1, 2, 3, 4, 5)
* .map(n => {
* if (n == 4) {
* throw 'four!';
* }
* return n;
* })
* .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
* .subscribe(x => console.log(x));
* // 1, 2, 3, I, II, III, IV, V
*
* @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
*
* Observable.of(1, 2, 3, 4, 5)
* .map(n => {
* if (n === 4) {
* throw 'four!';
* }
* return n;
* })
* .catch((err, caught) => caught)
* .take(30)
* .subscribe(x => console.log(x));
* // 1, 2, 3, 1, 2, 3, ...
*
* @example <caption>Throws a new error when the source Observable throws an error</caption>
*
* Observable.of(1, 2, 3, 4, 5)
* .map(n => {
* if (n == 4) {
* throw 'four!';
* }
* return n;
* })
* .catch(err => {
* throw 'error in source. Details: ' + err;
* })
* .subscribe(
* x => console.log(x),
* err => console.log(err)
* );
* // 1, 2, 3, error in source. Details: four!
*
* @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
* is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
* is returned by the `selector` will be used to continue the observable chain.
* @return {Observable} An observable that originates from either the source or the observable returned by the
* catch `selector` function.
* @method catch
* @name catch
* @owner Observable
*/
function _catch(selector) {
var operator = new CatchOperator(selector);
var caught = this.lift(operator);
return (operator.caught = caught);
}
exports._catch = _catch;
var CatchOperator = (function () {
function CatchOperator(selector) {
this.selector = selector;
}
CatchOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
};
return CatchOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var CatchSubscriber = (function (_super) {
__extends(CatchSubscriber, _super);
function CatchSubscriber(destination, selector, caught) {
_super.call(this, destination);
this.selector = selector;
this.caught = caught;
}
// NOTE: overriding `error` instead of `_error` because we don't want
// to have this flag this subscriber as `isStopped`. We can mimic the
// behavior of the RetrySubscriber (from the `retry` operator), where
// we unsubscribe from our source chain, reset our Subscriber flags,
// then subscribe to the selector result.
CatchSubscriber.prototype.error = function (err) {
if (!this.isStopped) {
var result = void 0;
try {
result = this.selector(err, this.caught);
}
catch (err2) {
_super.prototype.error.call(this, err2);
return;
}
this._unsubscribeAndRecycle();
this.add(subscribeToResult_1.subscribeToResult(this, result));
}
};
return CatchSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
//# sourceMappingURL=catch.js.map
/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var mergeAll_1 = __webpack_require__(77);
/* tslint:enable:max-line-length */
/**
* Converts a higher-order Observable into a first-order Observable by
* concatenating the inner Observables in order.
*
* <span class="informal">Flattens an Observable-of-Observables by putting one
* inner Observable after the other.</span>
*
* <img src="./img/concatAll.png" width="100%">
*
* Joins every Observable emitted by the source (a higher-order Observable), in
* a serial fashion. It subscribes to each inner Observable only after the
* previous inner Observable has completed, and merges all of their values into
* the returned observable.
*
* __Warning:__ If the source Observable emits Observables quickly and
* endlessly, and the inner Observables it emits generally complete slower than
* the source emits, you can run into memory issues as the incoming Observables
* collect in an unbounded buffer.
*
* Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set
* to `1`.
*
* @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var higherOrder = clicks.map(ev => Rx.Observable.interval(1000).take(4));
* var firstOrder = higherOrder.concatAll();
* firstOrder.subscribe(x => console.log(x));
*
* // Results in the following:
* // (results are not concurrent)
* // For every click on the "document" it will emit values 0 to 3 spaced
* // on a 1000ms interval
* // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
*
* @see {@link combineAll}
* @see {@link concat}
* @see {@link concatMap}
* @see {@link concatMapTo}
* @see {@link exhaust}
* @see {@link mergeAll}
* @see {@link switch}
* @see {@link zipAll}
*
* @return {Observable} An Observable emitting values from all the inner
* Observables concatenated.
* @method concatAll
* @owner Observable
*/
function concatAll() {
return this.lift(new mergeAll_1.MergeAllOperator(1));
}
exports.concatAll = concatAll;
//# sourceMappingURL=concatAll.js.map
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var mergeMap_1 = __webpack_require__(78);
/* tslint:enable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable, in a serialized fashion waiting for each one to complete before
* merging the next.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link concatAll}.</span>
*
* <img src="./img/concatMap.png" width="100%">
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an (so-called "inner") Observable. Each new inner Observable is
* concatenated with the previous inner Observable.
*
* __Warning:__ if source values arrive endlessly and faster than their
* corresponding inner Observables can complete, it will result in memory issues
* as inner Observables amass in an unbounded buffer waiting for their turn to
* be subscribed to.
*
* Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set
* to `1`.
*
* @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var result = clicks.concatMap(ev => Rx.Observable.interval(1000).take(4));
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // (results are not concurrent)
* // For every click on the "document" it will emit values 0 to 3 spaced
* // on a 1000ms interval
* // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
*
* @see {@link concat}
* @see {@link concatAll}
* @see {@link concatMapTo}
* @see {@link exhaustMap}
* @see {@link mergeMap}
* @see {@link switchMap}
*
* @param {function(value: T, ?index: number): ObservableInput} project A function
* that, when applied to an item emitted by the source Observable, returns an
* Observable.
* @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
* A function to produce the value on the output Observable based on the values
* and the indices of the source (outer) emission and the inner Observable
* emission. The arguments passed to this function are:
* - `outerValue`: the value that came from the source
* - `innerValue`: the value that came from the projected Observable
* - `outerIndex`: the "index" of the value that came from the source
* - `innerIndex`: the "index" of the value from the projected Observable
* @return {Observable} An observable of values merged from the projected
* Observables as they were subscribed to, one at a time. Optionally, these
* values may have been projected from a passed `projectResult` argument.
* @return {Observable} An Observable that emits the result of applying the
* projection function (and the optional `resultSelector`) to each item emitted
* by the source Observable and taking values from each projected inner
* Observable sequentially.
* @method concatMap
* @owner Observable
*/
function concatMap(project, resultSelector) {
return this.lift(new mergeMap_1.MergeMapOperator(project, resultSelector, 1));
}
exports.concatMap = concatMap;
//# sourceMappingURL=concatMap.js.map
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
var async_1 = __webpack_require__(37);
/**
* Emits a value from the source Observable only after a particular time span
* has passed without another source emission.
*
* <span class="informal">It's like {@link delay}, but passes only the most
* recent value from each burst of emissions.</span>
*
* <img src="./img/debounceTime.png" width="100%">
*
* `debounceTime` delays values emitted by the source Observable, but drops
* previous pending delayed emissions if a new value arrives on the source
* Observable. This operator keeps track of the most recent value from the
* source Observable, and emits that only when `dueTime` enough time has passed
* without any other value appearing on the source Observable. If a new value
* appears before `dueTime` silence occurs, the previous value will be dropped
* and will not be emitted on the output Observable.
*
* This is a rate-limiting operator, because it is impossible for more than one
* value to be emitted in any time window of duration `dueTime`, but it is also
* a delay-like operator since output emissions do not occur at the same time as
* they did on the source Observable. Optionally takes a {@link IScheduler} for
* managing timers.
*
* @example <caption>Emit the most recent click after a burst of clicks</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var result = clicks.debounceTime(1000);
* result.subscribe(x => console.log(x));
*
* @see {@link auditTime}
* @see {@link debounce}
* @see {@link delay}
* @see {@link sampleTime}
* @see {@link throttleTime}
*
* @param {number} dueTime The timeout duration in milliseconds (or the time
* unit determined internally by the optional `scheduler`) for the window of
* time required to wait for emission silence before emitting the most recent
* source value.
* @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
* managing the timers that handle the timeout for each value.
* @return {Observable} An Observable that delays the emissions of the source
* Observable by the specified `dueTime`, and may drop some values if they occur
* too frequently.
* @method debounceTime
* @owner Observable
*/
function debounceTime(dueTime, scheduler) {
if (scheduler === void 0) { scheduler = async_1.async; }
return this.lift(new DebounceTimeOperator(dueTime, scheduler));
}
exports.debounceTime = debounceTime;
var DebounceTimeOperator = (function () {
function DebounceTimeOperator(dueTime, scheduler) {
this.dueTime = dueTime;
this.scheduler = scheduler;
}
DebounceTimeOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
};
return DebounceTimeOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var DebounceTimeSubscriber = (function (_super) {
__extends(DebounceTimeSubscriber, _super);
function DebounceTimeSubscriber(destination, dueTime, scheduler) {
_super.call(this, destination);
this.dueTime = dueTime;
this.scheduler = scheduler;
this.debouncedSubscription = null;
this.lastValue = null;
this.hasValue = false;
}
DebounceTimeSubscriber.prototype._next = function (value) {
this.clearDebounce();
this.lastValue = value;
this.hasValue = true;
this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
};
DebounceTimeSubscriber.prototype._complete = function () {
this.debouncedNext();
this.destination.complete();
};
DebounceTimeSubscriber.prototype.debouncedNext = function () {
this.clearDebounce();
if (this.hasValue) {
this.destination.next(this.lastValue);
this.lastValue = null;
this.hasValue = false;
}
};
DebounceTimeSubscriber.prototype.clearDebounce = function () {
var debouncedSubscription = this.debouncedSubscription;
if (debouncedSubscription !== null) {
this.remove(debouncedSubscription);
debouncedSubscription.unsubscribe();
this.debouncedSubscription = null;
}
};
return DebounceTimeSubscriber;
}(Subscriber_1.Subscriber));
function dispatchNext(subscriber) {
subscriber.debouncedNext();
}
//# sourceMappingURL=debounceTime.js.map
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var async_1 = __webpack_require__(37);
var isDate_1 = __webpack_require__(114);
var Subscriber_1 = __webpack_require__(5);
var Notification_1 = __webpack_require__(102);
/**
* Delays the emission of items from the source Observable by a given timeout or
* until a given Date.
*
* <span class="informal">Time shifts each item by some specified amount of
* milliseconds.</span>
*
* <img src="./img/delay.png" width="100%">
*
* If the delay argument is a Number, this operator time shifts the source
* Observable by that amount of time expressed in milliseconds. The relative
* time intervals between the values are preserved.
*
* If the delay argument is a Date, this operator time shifts the start of the
* Observable execution until the given date occurs.
*
* @example <caption>Delay each click by one second</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
* delayedClicks.subscribe(x => console.log(x));
*
* @example <caption>Delay all clicks until a future date happens</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var date = new Date('March 15, 2050 12:00:00'); // in the future
* var delayedClicks = clicks.delay(date); // click emitted only after that date
* delayedClicks.subscribe(x => console.log(x));
*
* @see {@link debounceTime}
* @see {@link delayWhen}
*
* @param {number|Date} delay The delay duration in milliseconds (a `number`) or
* a `Date` until which the emission of the source items is delayed.
* @param {Scheduler} [scheduler=async] The IScheduler to use for
* managing the timers that handle the time-shift for each item.
* @return {Observable} An Observable that delays the emissions of the source
* Observable by the specified timeout or Date.
* @method delay
* @owner Observable
*/
function delay(delay, scheduler) {
if (scheduler === void 0) { scheduler = async_1.async; }
var absoluteDelay = isDate_1.isDate(delay);
var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
return this.lift(new DelayOperator(delayFor, scheduler));
}
exports.delay = delay;
var DelayOperator = (function () {
function DelayOperator(delay, scheduler) {
this.delay = delay;
this.scheduler = scheduler;
}
DelayOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
};
return DelayOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var DelaySubscriber = (function (_super) {
__extends(DelaySubscriber, _super);
function DelaySubscriber(destination, delay, scheduler) {
_super.call(this, destination);
this.delay = delay;
this.scheduler = scheduler;
this.queue = [];
this.active = false;
this.errored = false;
}
DelaySubscriber.dispatch = function (state) {
var source = state.source;
var queue = source.queue;
var scheduler = state.scheduler;
var destination = state.destination;
while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
queue.shift().notification.observe(destination);
}
if (queue.length > 0) {
var delay_1 = Math.max(0, queue[0].time - scheduler.now());
this.schedule(state, delay_1);
}
else {
source.active = false;
}
};
DelaySubscriber.prototype._schedule = function (scheduler) {
this.active = true;
this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
source: this, destination: this.destination, scheduler: scheduler
}));
};
DelaySubscriber.prototype.scheduleNotification = function (notification) {
if (this.errored === true) {
return;
}
var scheduler = this.scheduler;
var message = new DelayMessage(scheduler.now() + this.delay, notification);
this.queue.push(message);
if (this.active === false) {
this._schedule(scheduler);
}
};
DelaySubscriber.prototype._next = function (value) {
this.scheduleNotification(Notification_1.Notification.createNext(value));
};
DelaySubscriber.prototype._error = function (err) {
this.errored = true;
this.queue = [];
this.destination.error(err);
};
DelaySubscriber.prototype._complete = function () {
this.scheduleNotification(Notification_1.Notification.createComplete());
};
return DelaySubscriber;
}(Subscriber_1.Subscriber));
var DelayMessage = (function () {
function DelayMessage(time, notification) {
this.time = time;
this.notification = notification;
}
return DelayMessage;
}());
//# sourceMappingURL=delay.js.map
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
var tryCatch_1 = __webpack_require__(49);
var errorObject_1 = __webpack_require__(38);
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
*
* If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
*
* If a comparator function is not provided, an equality check is used by default.
*
* @example <caption>A simple example with numbers</caption>
* Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
* .distinctUntilChanged()
* .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
*
* @example <caption>An example using a compare function</caption>
* interface Person {
* age: number,
* name: string
* }
*
* Observable.of<Person>(
* { age: 4, name: 'Foo'},
* { age: 7, name: 'Bar'},
* { age: 5, name: 'Foo'})
* { age: 6, name: 'Foo'})
* .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
* .subscribe(x => console.log(x));
*
* // displays:
* // { age: 4, name: 'Foo' }
* // { age: 7, name: 'Bar' }
* // { age: 5, name: 'Foo' }
*
* @see {@link distinct}
* @see {@link distinctUntilKeyChanged}
*
* @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
* @return {Observable} An Observable that emits items from the source Observable with distinct values.
* @method distinctUntilChanged
* @owner Observable
*/
function distinctUntilChanged(compare, keySelector) {
return this.lift(new DistinctUntilChangedOperator(compare, keySelector));
}
exports.distinctUntilChanged = distinctUntilChanged;
var DistinctUntilChangedOperator = (function () {
function DistinctUntilChangedOperator(compare, keySelector) {
this.compare = compare;
this.keySelector = keySelector;
}
DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
};
return DistinctUntilChangedOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var DistinctUntilChangedSubscriber = (function (_super) {
__extends(DistinctUntilChangedSubscriber, _super);
function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
_super.call(this, destination);
this.keySelector = keySelector;
this.hasKey = false;
if (typeof compare === 'function') {
this.compare = compare;
}
}
DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
return x === y;
};
DistinctUntilChangedSubscriber.prototype._next = function (value) {
var keySelector = this.keySelector;
var key = value;
if (keySelector) {
key = tryCatch_1.tryCatch(this.keySelector)(value);
if (key === errorObject_1.errorObject) {
return this.destination.error(errorObject_1.errorObject.e);
}
}
var result = false;
if (this.hasKey) {
result = tryCatch_1.tryCatch(this.compare)(this.key, key);
if (result === errorObject_1.errorObject) {
return this.destination.error(errorObject_1.errorObject.e);
}
}
else {
this.hasKey = true;
}
if (Boolean(result) === false) {
this.key = key;
this.destination.next(value);
}
};
return DistinctUntilChangedSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=distinctUntilChanged.js.map
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/* tslint:enable:max-line-length */
/**
* Perform a side effect for every emission on the source Observable, but return
* an Observable that is identical to the source.
*
* <span class="informal">Intercepts each emission on the source and runs a
* function, but returns an output which is identical to the source as long as errors don't occur.</span>
*
* <img src="./img/do.png" width="100%">
*
* Returns a mirrored Observable of the source Observable, but modified so that
* the provided Observer is called to perform a side effect for every value,
* error, and completion emitted by the source. Any errors that are thrown in
* the aforementioned Observer or handlers are safely sent down the error path
* of the output Observable.
*
* This operator is useful for debugging your Observables for the correct values
* or performing other side effects.
*
* Note: this is different to a `subscribe` on the Observable. If the Observable
* returned by `do` is not subscribed, the side effects specified by the
* Observer will never happen. `do` therefore simply spies on existing
* execution, it does not trigger an execution to happen like `subscribe` does.
*
* @example <caption>Map every every click to the clientX position of that click, while also logging the click event</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var positions = clicks
* .do(ev => console.log(ev))
* .map(ev => ev.clientX);
* positions.subscribe(x => console.log(x));
*
* @see {@link map}
* @see {@link subscribe}
*
* @param {Observer|function} [nextOrObserver] A normal Observer object or a
* callback for `next`.
* @param {function} [error] Callback for errors in the source.
* @param {function} [complete] Callback for the completion of the source.
* @return {Observable} An Observable identical to the source, but runs the
* specified Observer or callback(s) for each item.
* @method do
* @name do
* @owner Observable
*/
function _do(nextOrObserver, error, complete) {
return this.lift(new DoOperator(nextOrObserver, error, complete));
}
exports._do = _do;
var DoOperator = (function () {
function DoOperator(nextOrObserver, error, complete) {
this.nextOrObserver = nextOrObserver;
this.error = error;
this.complete = complete;
}
DoOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
};
return DoOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var DoSubscriber = (function (_super) {
__extends(DoSubscriber, _super);
function DoSubscriber(destination, nextOrObserver, error, complete) {
_super.call(this, destination);
var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
safeSubscriber.syncErrorThrowable = true;
this.add(safeSubscriber);
this.safeSubscriber = safeSubscriber;
}
DoSubscriber.prototype._next = function (value) {
var safeSubscriber = this.safeSubscriber;
safeSubscriber.next(value);
if (safeSubscriber.syncErrorThrown) {
this.destination.error(safeSubscriber.syncErrorValue);
}
else {
this.destination.next(value);
}
};
DoSubscriber.prototype._error = function (err) {
var safeSubscriber = this.safeSubscriber;
safeSubscriber.error(err);
if (safeSubscriber.syncErrorThrown) {
this.destination.error(safeSubscriber.syncErrorValue);
}
else {
this.destination.error(err);
}
};
DoSubscriber.prototype._complete = function () {
var safeSubscriber = this.safeSubscriber;
safeSubscriber.complete();
if (safeSubscriber.syncErrorThrown) {
this.destination.error(safeSubscriber.syncErrorValue);
}
else {
this.destination.complete();
}
};
return DoSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=do.js.map
/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/**
* Returns an Observable that emits whether or not every item of the source satisfies the condition specified.
*
* @example <caption>A simple example emitting true if all elements are less than 5, false otherwise</caption>
* Observable.of(1, 2, 3, 4, 5, 6)
* .every(x => x < 5)
* .subscribe(x => console.log(x)); // -> false
*
* @param {function} predicate A function for determining if an item meets a specified condition.
* @param {any} [thisArg] Optional object to use for `this` in the callback.
* @return {Observable} An Observable of booleans that determines if all items of the source Observable meet the condition specified.
* @method every
* @owner Observable
*/
function every(predicate, thisArg) {
return this.lift(new EveryOperator(predicate, thisArg, this));
}
exports.every = every;
var EveryOperator = (function () {
function EveryOperator(predicate, thisArg, source) {
this.predicate = predicate;
this.thisArg = thisArg;
this.source = source;
}
EveryOperator.prototype.call = function (observer, source) {
return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
};
return EveryOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var EverySubscriber = (function (_super) {
__extends(EverySubscriber, _super);
function EverySubscriber(destination, predicate, thisArg, source) {
_super.call(this, destination);
this.predicate = predicate;
this.thisArg = thisArg;
this.source = source;
this.index = 0;
this.thisArg = thisArg || this;
}
EverySubscriber.prototype.notifyComplete = function (everyValueMatch) {
this.destination.next(everyValueMatch);
this.destination.complete();
};
EverySubscriber.prototype._next = function (value) {
var result = false;
try {
result = this.predicate.call(this.thisArg, value, this.index++, this.source);
}
catch (err) {
this.destination.error(err);
return;
}
if (!result) {
this.notifyComplete(false);
}
};
EverySubscriber.prototype._complete = function () {
this.notifyComplete(true);
};
return EverySubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=every.js.map
/***/ }),
/* 311 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
var EmptyError_1 = __webpack_require__(82);
/**
* Emits only the first value (or the first value that meets some condition)
* emitted by the source Observable.
*
* <span class="informal">Emits only the first value. Or emits only the first
* value that passes some test.</span>
*
* <img src="./img/first.png" width="100%">
*
* If called with no arguments, `first` emits the first value of the source
* Observable, then completes. If called with a `predicate` function, `first`
* emits the first value of the source that matches the specified condition. It
* may also take a `resultSelector` function to produce the output value from
* the input value, and a `defaultValue` to emit in case the source completes
* before it is able to emit a valid value. Throws an error if `defaultValue`
* was not provided and a matching element is not found.
*
* @example <caption>Emit only the first click that happens on the DOM</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var result = clicks.first();
* result.subscribe(x => console.log(x));
*
* @example <caption>Emits the first click that happens on a DIV</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var result = clicks.first(ev => ev.target.tagName === 'DIV');
* result.subscribe(x => console.log(x));
*
* @see {@link filter}
* @see {@link find}
* @see {@link take}
*
* @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
* callback if the Observable completes before any `next` notification was sent.
*
* @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
* An optional function called with each item to test for condition matching.
* @param {function(value: T, index: number): R} [resultSelector] A function to
* produce the value on the output Observable based on the values
* and the indices of the source Observable. The arguments passed to this
* function are:
* - `value`: the value that was emitted on the source.
* - `index`: the "index" of the value from the source.
* @param {R} [defaultValue] The default value emitted in case no valid value
* was found on the source.
* @return {Observable<T|R>} An Observable of the first item that matches the
* condition.
* @method first
* @owner Observable
*/
function first(predicate, resultSelector, defaultValue) {
return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this));
}
exports.first = first;
var FirstOperator = (function () {
function FirstOperator(predicate, resultSelector, defaultValue, source) {
this.predicate = predicate;
this.resultSelector = resultSelector;
this.defaultValue = defaultValue;
this.source = source;
}
FirstOperator.prototype.call = function (observer, source) {
return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
};
return FirstOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var FirstSubscriber = (function (_super) {
__extends(FirstSubscriber, _super);
function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
_super.call(this, destination);
this.predicate = predicate;
this.resultSelector = resultSelector;
this.defaultValue = defaultValue;
this.source = source;
this.index = 0;
this.hasCompleted = false;
this._emitted = false;
}
FirstSubscriber.prototype._next = function (value) {
var index = this.index++;
if (this.predicate) {
this._tryPredicate(value, index);
}
else {
this._emit(value, index);
}
};
FirstSubscriber.prototype._tryPredicate = function (value, index) {
var result;
try {
result = this.predicate(value, index, this.source);
}
catch (err) {
this.destination.error(err);
return;
}
if (result) {
this._emit(value, index);
}
};
FirstSubscriber.prototype._emit = function (value, index) {
if (this.resultSelector) {
this._tryResultSelector(value, index);
return;
}
this._emitFinal(value);
};
FirstSubscriber.prototype._tryResultSelector = function (value, index) {
var result;
try {
result = this.resultSelector(value, index);
}
catch (err) {
this.destination.error(err);
return;
}
this._emitFinal(result);
};
FirstSubscriber.prototype._emitFinal = function (value) {
var destination = this.destination;
if (!this._emitted) {
this._emitted = true;
destination.next(value);
destination.complete();
this.hasCompleted = true;
}
};
FirstSubscriber.prototype._complete = function () {
var destination = this.destination;
if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
destination.next(this.defaultValue);
destination.complete();
}
else if (!this.hasCompleted) {
destination.error(new EmptyError_1.EmptyError);
}
};
return FirstSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=first.js.map
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
var EmptyError_1 = __webpack_require__(82);
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits only the last item emitted by the source Observable.
* It optionally takes a predicate function as a parameter, in which case, rather than emitting
* the last item from the source Observable, the resulting Observable will emit the last item
* from the source Observable that satisfies the predicate.
*
* <img src="./img/last.png" width="100%">
*
* @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
* callback if the Observable completes before any `next` notification was sent.
* @param {function} predicate - The condition any source emitted item has to satisfy.
* @return {Observable} An Observable that emits only the last item satisfying the given condition
* from the source, or an NoSuchElementException if no such items are emitted.
* @throws - Throws if no items that match the predicate are emitted by the source Observable.
* @method last
* @owner Observable
*/
function last(predicate, resultSelector, defaultValue) {
return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this));
}
exports.last = last;
var LastOperator = (function () {
function LastOperator(predicate, resultSelector, defaultValue, source) {
this.predicate = predicate;
this.resultSelector = resultSelector;
this.defaultValue = defaultValue;
this.source = source;
}
LastOperator.prototype.call = function (observer, source) {
return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
};
return LastOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var LastSubscriber = (function (_super) {
__extends(LastSubscriber, _super);
function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
_super.call(this, destination);
this.predicate = predicate;
this.resultSelector = resultSelector;
this.defaultValue = defaultValue;
this.source = source;
this.hasValue = false;
this.index = 0;
if (typeof defaultValue !== 'undefined') {
this.lastValue = defaultValue;
this.hasValue = true;
}
}
LastSubscriber.prototype._next = function (value) {
var index = this.index++;
if (this.predicate) {
this._tryPredicate(value, index);
}
else {
if (this.resultSelector) {
this._tryResultSelector(value, index);
return;
}
this.lastValue = value;
this.hasValue = true;
}
};
LastSubscriber.prototype._tryPredicate = function (value, index) {
var result;
try {
result = this.predicate(value, index, this.source);
}
catch (err) {
this.destination.error(err);
return;
}
if (result) {
if (this.resultSelector) {
this._tryResultSelector(value, index);
return;
}
this.lastValue = value;
this.hasValue = true;
}
};
LastSubscriber.prototype._tryResultSelector = function (value, index) {
var result;
try {
result = this.resultSelector(value, index);
}
catch (err) {
this.destination.error(err);
return;
}
this.lastValue = result;
this.hasValue = true;
};
LastSubscriber.prototype._complete = function () {
var destination = this.destination;
if (this.hasValue) {
destination.next(this.lastValue);
destination.complete();
}
else {
destination.error(new EmptyError_1.EmptyError);
}
};
return LastSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=last.js.map
/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Observable_1 = __webpack_require__(0);
var ArrayObservable_1 = __webpack_require__(75);
var mergeAll_1 = __webpack_require__(77);
var isScheduler_1 = __webpack_require__(48);
/* tslint:enable:max-line-length */
/**
* Creates an output Observable which concurrently emits all values from every
* given input Observable.
*
* <span class="informal">Flattens multiple Observables together by blending
* their values into one Observable.</span>
*
* <img src="./img/merge.png" width="100%">
*
* `merge` subscribes to each given input Observable (either the source or an
* Observable given as argument), and simply forwards (without doing any
* transformation) all the values from all the input Observables to the output
* Observable. The output Observable only completes once all input Observables
* have completed. Any error delivered by an input Observable will be immediately
* emitted on the output Observable.
*
* @example <caption>Merge together two Observables: 1s interval and clicks</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var timer = Rx.Observable.interval(1000);
* var clicksOrTimer = clicks.merge(timer);
* clicksOrTimer.subscribe(x => console.log(x));
*
* @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
* var timer1 = Rx.Observable.interval(1000).take(10);
* var timer2 = Rx.Observable.interval(2000).take(6);
* var timer3 = Rx.Observable.interval(500).take(10);
* var concurrent = 2; // the argument
* var merged = timer1.merge(timer2, timer3, concurrent);
* merged.subscribe(x => console.log(x));
*
* @see {@link mergeAll}
* @see {@link mergeMap}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
*
* @param {ObservableInput} other An input Observable to merge with the source
* Observable. More than one input Observables may be given as argument.
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
* Observables being subscribed to concurrently.
* @param {Scheduler} [scheduler=null] The IScheduler to use for managing
* concurrency of input Observables.
* @return {Observable} An Observable that emits items that are the result of
* every input Observable.
* @method merge
* @owner Observable
*/
function merge() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i - 0] = arguments[_i];
}
return this.lift.call(mergeStatic.apply(void 0, [this].concat(observables)));
}
exports.merge = merge;
/* tslint:enable:max-line-length */
/**
* Creates an output Observable which concurrently emits all values from every
* given input Observable.
*
* <span class="informal">Flattens multiple Observables together by blending
* their values into one Observable.</span>
*
* <img src="./img/merge.png" width="100%">
*
* `merge` subscribes to each given input Observable (as arguments), and simply
* forwards (without doing any transformation) all the values from all the input
* Observables to the output Observable. The output Observable only completes
* once all input Observables have completed. Any error delivered by an input
* Observable will be immediately emitted on the output Observable.
*
* @example <caption>Merge together two Observables: 1s interval and clicks</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var timer = Rx.Observable.interval(1000);
* var clicksOrTimer = Rx.Observable.merge(clicks, timer);
* clicksOrTimer.subscribe(x => console.log(x));
*
* // Results in the following:
* // timer will emit ascending values, one every second(1000ms) to console
* // clicks logs MouseEvents to console everytime the "document" is clicked
* // Since the two streams are merged you see these happening
* // as they occur.
*
* @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
* var timer1 = Rx.Observable.interval(1000).take(10);
* var timer2 = Rx.Observable.interval(2000).take(6);
* var timer3 = Rx.Observable.interval(500).take(10);
* var concurrent = 2; // the argument
* var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
* merged.subscribe(x => console.log(x));
*
* // Results in the following:
* // - First timer1 and timer2 will run concurrently
* // - timer1 will emit a value every 1000ms for 10 iterations
* // - timer2 will emit a value every 2000ms for 6 iterations
* // - after timer1 hits it's max iteration, timer2 will
* // continue, and timer3 will start to run concurrently with timer2
* // - when timer2 hits it's max iteration it terminates, and
* // timer3 will continue to emit a value every 500ms until it is complete
*
* @see {@link mergeAll}
* @see {@link mergeMap}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
*
* @param {...ObservableInput} observables Input Observables to merge together.
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
* Observables being subscribed to concurrently.
* @param {Scheduler} [scheduler=null] The IScheduler to use for managing
* concurrency of input Observables.
* @return {Observable} an Observable that emits items that are the result of
* every input Observable.
* @static true
* @name merge
* @owner Observable
*/
function mergeStatic() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i - 0] = arguments[_i];
}
var concurrent = Number.POSITIVE_INFINITY;
var scheduler = null;
var last = observables[observables.length - 1];
if (isScheduler_1.isScheduler(last)) {
scheduler = observables.pop();
if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
concurrent = observables.pop();
}
}
else if (typeof last === 'number') {
concurrent = observables.pop();
}
if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
return observables[0];
}
return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent));
}
exports.mergeStatic = mergeStatic;
//# sourceMappingURL=merge.js.map
/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ConnectableObservable_1 = __webpack_require__(288);
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits the results of invoking a specified selector on items
* emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
*
* <img src="./img/multicast.png" width="100%">
*
* @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
* which the source sequence's elements will be multicast to the selector function
* or Subject to push source elements into.
* @param {Function} [selector] - Optional selector function that can use the multicasted source stream
* as many times as needed, without causing multiple subscriptions to the source stream.
* Subscribers to the given source will receive all notifications of the source from the
* time of the subscription forward.
* @return {Observable} An Observable that emits the results of invoking the selector
* on the items emitted by a `ConnectableObservable` that shares a single subscription to
* the underlying stream.
* @method multicast
* @owner Observable
*/
function multicast(subjectOrSubjectFactory, selector) {
var subjectFactory;
if (typeof subjectOrSubjectFactory === 'function') {
subjectFactory = subjectOrSubjectFactory;
}
else {
subjectFactory = function subjectFactory() {
return subjectOrSubjectFactory;
};
}
if (typeof selector === 'function') {
return this.lift(new MulticastOperator(subjectFactory, selector));
}
var connectable = Object.create(this, ConnectableObservable_1.connectableObservableDescriptor);
connectable.source = this;
connectable.subjectFactory = subjectFactory;
return connectable;
}
exports.multicast = multicast;
var MulticastOperator = (function () {
function MulticastOperator(subjectFactory, selector) {
this.subjectFactory = subjectFactory;
this.selector = selector;
}
MulticastOperator.prototype.call = function (subscriber, source) {
var selector = this.selector;
var subject = this.subjectFactory();
var subscription = selector(subject).subscribe(subscriber);
subscription.add(source.subscribe(subject));
return subscription;
};
return MulticastOperator;
}());
exports.MulticastOperator = MulticastOperator;
//# sourceMappingURL=multicast.js.map
/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
var Notification_1 = __webpack_require__(102);
/**
* @see {@link Notification}
*
* @param scheduler
* @param delay
* @return {Observable<R>|WebSocketSubject<T>|Observable<T>}
* @method observeOn
* @owner Observable
*/
function observeOn(scheduler, delay) {
if (delay === void 0) { delay = 0; }
return this.lift(new ObserveOnOperator(scheduler, delay));
}
exports.observeOn = observeOn;
var ObserveOnOperator = (function () {
function ObserveOnOperator(scheduler, delay) {
if (delay === void 0) { delay = 0; }
this.scheduler = scheduler;
this.delay = delay;
}
ObserveOnOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
};
return ObserveOnOperator;
}());
exports.ObserveOnOperator = ObserveOnOperator;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var ObserveOnSubscriber = (function (_super) {
__extends(ObserveOnSubscriber, _super);
function ObserveOnSubscriber(destination, scheduler, delay) {
if (delay === void 0) { delay = 0; }
_super.call(this, destination);
this.scheduler = scheduler;
this.delay = delay;
}
ObserveOnSubscriber.dispatch = function (arg) {
var notification = arg.notification, destination = arg.destination;
notification.observe(destination);
this.unsubscribe();
};
ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
};
ObserveOnSubscriber.prototype._next = function (value) {
this.scheduleMessage(Notification_1.Notification.createNext(value));
};
ObserveOnSubscriber.prototype._error = function (err) {
this.scheduleMessage(Notification_1.Notification.createError(err));
};
ObserveOnSubscriber.prototype._complete = function () {
this.scheduleMessage(Notification_1.Notification.createComplete());
};
return ObserveOnSubscriber;
}(Subscriber_1.Subscriber));
exports.ObserveOnSubscriber = ObserveOnSubscriber;
var ObserveOnMessage = (function () {
function ObserveOnMessage(notification, destination) {
this.notification = notification;
this.destination = destination;
}
return ObserveOnMessage;
}());
exports.ObserveOnMessage = ObserveOnMessage;
//# sourceMappingURL=observeOn.js.map
/***/ }),
/* 316 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/* tslint:enable:max-line-length */
/**
* Applies an accumulator function over the source Observable, and returns the
* accumulated result when the source completes, given an optional seed value.
*
* <span class="informal">Combines together all values emitted on the source,
* using an accumulator function that knows how to join a new source value into
* the accumulation from the past.</span>
*
* <img src="./img/reduce.png" width="100%">
*
* Like
* [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),
* `reduce` applies an `accumulator` function against an accumulation and each
* value of the source Observable (from the past) to reduce it to a single
* value, emitted on the output Observable. Note that `reduce` will only emit
* one value, only when the source Observable completes. It is equivalent to
* applying operator {@link scan} followed by operator {@link last}.
*
* Returns an Observable that applies a specified `accumulator` function to each
* item emitted by the source Observable. If a `seed` value is specified, then
* that value will be used as the initial value for the accumulator. If no seed
* value is specified, the first item of the source is used as the seed.
*
* @example <caption>Count the number of click events that happened in 5 seconds</caption>
* var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click')
* .takeUntil(Rx.Observable.interval(5000));
* var ones = clicksInFiveSeconds.mapTo(1);
* var seed = 0;
* var count = ones.reduce((acc, one) => acc + one, seed);
* count.subscribe(x => console.log(x));
*
* @see {@link count}
* @see {@link expand}
* @see {@link mergeScan}
* @see {@link scan}
*
* @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function
* called on each source value.
* @param {R} [seed] The initial accumulation value.
* @return {Observable<R>} An Observable that emits a single value that is the
* result of accumulating the values emitted by the source Observable.
* @method reduce
* @owner Observable
*/
function reduce(accumulator, seed) {
var hasSeed = false;
// providing a seed of `undefined` *should* be valid and trigger
// hasSeed! so don't use `seed !== undefined` checks!
// For this reason, we have to check it here at the original call site
// otherwise inside Operator/Subscriber we won't know if `undefined`
// means they didn't provide anything or if they literally provided `undefined`
if (arguments.length >= 2) {
hasSeed = true;
}
return this.lift(new ReduceOperator(accumulator, seed, hasSeed));
}
exports.reduce = reduce;
var ReduceOperator = (function () {
function ReduceOperator(accumulator, seed, hasSeed) {
if (hasSeed === void 0) { hasSeed = false; }
this.accumulator = accumulator;
this.seed = seed;
this.hasSeed = hasSeed;
}
ReduceOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new ReduceSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
};
return ReduceOperator;
}());
exports.ReduceOperator = ReduceOperator;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var ReduceSubscriber = (function (_super) {
__extends(ReduceSubscriber, _super);
function ReduceSubscriber(destination, accumulator, seed, hasSeed) {
_super.call(this, destination);
this.accumulator = accumulator;
this.hasSeed = hasSeed;
this.index = 0;
this.hasValue = false;
this.acc = seed;
if (!this.hasSeed) {
this.index++;
}
}
ReduceSubscriber.prototype._next = function (value) {
if (this.hasValue || (this.hasValue = this.hasSeed)) {
this._tryReduce(value);
}
else {
this.acc = value;
this.hasValue = true;
}
};
ReduceSubscriber.prototype._tryReduce = function (value) {
var result;
try {
result = this.accumulator(this.acc, value, this.index++);
}
catch (err) {
this.destination.error(err);
return;
}
this.acc = result;
};
ReduceSubscriber.prototype._complete = function () {
if (this.hasValue || this.hasSeed) {
this.destination.next(this.acc);
}
this.destination.complete();
};
return ReduceSubscriber;
}(Subscriber_1.Subscriber));
exports.ReduceSubscriber = ReduceSubscriber;
//# sourceMappingURL=reduce.js.map
/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
/**
* Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
* calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
* as a number parameter) rather than propagating the `error` call.
*
* <img src="./img/retry.png" width="100%">
*
* Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
* during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
* time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
* would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
* @param {number} count - Number of retry attempts before failing.
* @return {Observable} The source Observable modified with the retry logic.
* @method retry
* @owner Observable
*/
function retry(count) {
if (count === void 0) { count = -1; }
return this.lift(new RetryOperator(count, this));
}
exports.retry = retry;
var RetryOperator = (function () {
function RetryOperator(count, source) {
this.count = count;
this.source = source;
}
RetryOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
};
return RetryOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var RetrySubscriber = (function (_super) {
__extends(RetrySubscriber, _super);
function RetrySubscriber(destination, count, source) {
_super.call(this, destination);
this.count = count;
this.source = source;
}
RetrySubscriber.prototype.error = function (err) {
if (!this.isStopped) {
var _a = this, source = _a.source, count = _a.count;
if (count === 0) {
return _super.prototype.error.call(this, err);
}
else if (count > -1) {
this.count = count - 1;
}
source.subscribe(this._unsubscribeAndRecycle());
}
};
return RetrySubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=retry.js.map
/***/ }),
/* 318 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subject_1 = __webpack_require__(25);
var tryCatch_1 = __webpack_require__(49);
var errorObject_1 = __webpack_require__(38);
var OuterSubscriber_1 = __webpack_require__(24);
var subscribeToResult_1 = __webpack_require__(27);
/**
* Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
* calls `error`, this method will emit the Throwable that caused the error to the Observable returned from `notifier`.
* If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child
* subscription. Otherwise this method will resubscribe to the source Observable.
*
* <img src="./img/retryWhen.png" width="100%">
*
* @param {function(errors: Observable): Observable} notifier - Receives an Observable of notifications with which a
* user can `complete` or `error`, aborting the retry.
* @return {Observable} The source Observable modified with retry logic.
* @method retryWhen
* @owner Observable
*/
function retryWhen(notifier) {
return this.lift(new RetryWhenOperator(notifier, this));
}
exports.retryWhen = retryWhen;
var RetryWhenOperator = (function () {
function RetryWhenOperator(notifier, source) {
this.notifier = notifier;
this.source = source;
}
RetryWhenOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));
};
return RetryWhenOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var RetryWhenSubscriber = (function (_super) {
__extends(RetryWhenSubscriber, _super);
function RetryWhenSubscriber(destination, notifier, source) {
_super.call(this, destination);
this.notifier = notifier;
this.source = source;
}
RetryWhenSubscriber.prototype.error = function (err) {
if (!this.isStopped) {
var errors = this.errors;
var retries = this.retries;
var retriesSubscription = this.retriesSubscription;
if (!retries) {
errors = new Subject_1.Subject();
retries = tryCatch_1.tryCatch(this.notifier)(errors);
if (retries === errorObject_1.errorObject) {
return _super.prototype.error.call(this, errorObject_1.errorObject.e);
}
retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries);
}
else {
this.errors = null;
this.retriesSubscription = null;
}
this._unsubscribeAndRecycle();
this.errors = errors;
this.retries = retries;
this.retriesSubscription = retriesSubscription;
errors.next(err);
}
};
RetryWhenSubscriber.prototype._unsubscribe = function () {
var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;
if (errors) {
errors.unsubscribe();
this.errors = null;
}
if (retriesSubscription) {
retriesSubscription.unsubscribe();
this.retriesSubscription = null;
}
this.retries = null;
};
RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
var _a = this, errors = _a.errors, retries = _a.retries, retriesSubscription = _a.retriesSubscription;
this.errors = null;
this.retries = null;
this.retriesSubscription = null;
this._unsubscribeAndRecycle();
this.errors = errors;
this.retries = retries;
this.retriesSubscription = retriesSubscription;
this.source.subscribe(this);
};
return RetryWhenSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
//# sourceMappingURL=retryWhen.js.map
/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var multicast_1 = __webpack_require__(314);
var Subject_1 = __webpack_require__(25);
function shareSubjectFactory() {
return new Subject_1.Subject();
}
/**
* Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
* Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
* unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
* This is an alias for .publish().refCount().
*
* <img src="./img/share.png" width="100%">
*
* @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
* @method share
* @owner Observable
*/
function share() {
return multicast_1.multicast.call(this, shareSubjectFactory).refCount();
}
exports.share = share;
;
//# sourceMappingURL=share.js.map
/***/ }),
/* 320 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var OuterSubscriber_1 = __webpack_require__(24);
var subscribeToResult_1 = __webpack_require__(27);
/* tslint:enable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable, emitting values only from the most recently projected Observable.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link switch}.</span>
*
* <img src="./img/switchMap.png" width="100%">
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an (so-called "inner") Observable. Each time it observes one of these
* inner Observables, the output Observable begins emitting the items emitted by
* that inner Observable. When a new inner Observable is emitted, `switchMap`
* stops emitting items from the earlier-emitted inner Observable and begins
* emitting items from the new one. It continues to behave like this for
* subsequent inner Observables.
*
* @example <caption>Rerun an interval Observable on every click event</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
* result.subscribe(x => console.log(x));
*
* @see {@link concatMap}
* @see {@link exhaustMap}
* @see {@link mergeMap}
* @see {@link switch}
* @see {@link switchMapTo}
*
* @param {function(value: T, ?index: number): ObservableInput} project A function
* that, when applied to an item emitted by the source Observable, returns an
* Observable.
* @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
* A function to produce the value on the output Observable based on the values
* and the indices of the source (outer) emission and the inner Observable
* emission. The arguments passed to this function are:
* - `outerValue`: the value that came from the source
* - `innerValue`: the value that came from the projected Observable
* - `outerIndex`: the "index" of the value that came from the source
* - `innerIndex`: the "index" of the value from the projected Observable
* @return {Observable} An Observable that emits the result of applying the
* projection function (and the optional `resultSelector`) to each item emitted
* by the source Observable and taking only the values from the most recently
* projected inner Observable.
* @method switchMap
* @owner Observable
*/
function switchMap(project, resultSelector) {
return this.lift(new SwitchMapOperator(project, resultSelector));
}
exports.switchMap = switchMap;
var SwitchMapOperator = (function () {
function SwitchMapOperator(project, resultSelector) {
this.project = project;
this.resultSelector = resultSelector;
}
SwitchMapOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
};
return SwitchMapOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var SwitchMapSubscriber = (function (_super) {
__extends(SwitchMapSubscriber, _super);
function SwitchMapSubscriber(destination, project, resultSelector) {
_super.call(this, destination);
this.project = project;
this.resultSelector = resultSelector;
this.index = 0;
}
SwitchMapSubscriber.prototype._next = function (value) {
var result;
var index = this.index++;
try {
result = this.project(value, index);
}
catch (error) {
this.destination.error(error);
return;
}
this._innerSub(result, value, index);
};
SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
var innerSubscription = this.innerSubscription;
if (innerSubscription) {
innerSubscription.unsubscribe();
}
this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
};
SwitchMapSubscriber.prototype._complete = function () {
var innerSubscription = this.innerSubscription;
if (!innerSubscription || innerSubscription.closed) {
_super.prototype._complete.call(this);
}
};
SwitchMapSubscriber.prototype._unsubscribe = function () {
this.innerSubscription = null;
};
SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
this.remove(innerSub);
this.innerSubscription = null;
if (this.isStopped) {
_super.prototype._complete.call(this);
}
};
SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
if (this.resultSelector) {
this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
}
else {
this.destination.next(innerValue);
}
};
SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
var result;
try {
result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
};
return SwitchMapSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
//# sourceMappingURL=switchMap.js.map
/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = __webpack_require__(5);
var ArgumentOutOfRangeError_1 = __webpack_require__(325);
var EmptyObservable_1 = __webpack_require__(46);
/**
* Emits only the first `count` values emitted by the source Observable.
*
* <span class="informal">Takes the first `count` values from the source, then
* completes.</span>
*
* <img src="./img/take.png" width="100%">
*
* `take` returns an Observable that emits only the first `count` values emitted
* by the source Observable. If the source emits fewer than `count` values then
* all of its values are emitted. After that, it completes, regardless if the
* source completes.
*
* @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
* var interval = Rx.Observable.interval(1000);
* var five = interval.take(5);
* five.subscribe(x => console.log(x));
*
* @see {@link takeLast}
* @see {@link takeUntil}
* @see {@link takeWhile}
* @see {@link skip}
*
* @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
* ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
*
* @param {number} count The maximum number of `next` values to emit.
* @return {Observable<T>} An Observable that emits only the first `count`
* values emitted by the source Observable, or all of the values from the source
* if the source emits fewer than `count` values.
* @method take
* @owner Observable
*/
function take(count) {
if (count === 0) {
return new EmptyObservable_1.EmptyObservable();
}
else {
return this.lift(new TakeOperator(count));
}
}
exports.take = take;
var TakeOperator = (function () {
function TakeOperator(total) {
this.total = total;
if (this.total < 0) {
throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
}
}
TakeOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new TakeSubscriber(subscriber, this.total));
};
return TakeOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var TakeSubscriber = (function (_super) {
__extends(TakeSubscriber, _super);
function TakeSubscriber(destination, total) {
_super.call(this, destination);
this.total = total;
this.count = 0;
}
TakeSubscriber.prototype._next = function (value) {
var total = this.total;
var count = ++this.count;
if (count <= total) {
this.destination.next(value);
if (count === total) {
this.destination.complete();
this.unsubscribe();
}
}
};
return TakeSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=take.js.map
/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscription_1 = __webpack_require__(26);
/**
* A unit of work to be executed in a {@link Scheduler}. An action is typically
* created from within a Scheduler and an RxJS user does not need to concern
* themselves about creating and manipulating an Action.
*
* ```ts
* class Action<T> extends Subscription {
* new (scheduler: Scheduler, work: (state?: T) => void);
* schedule(state?: T, delay: number = 0): Subscription;
* }
* ```
*
* @class Action<T>
*/
var Action = (function (_super) {
__extends(Action, _super);
function Action(scheduler, work) {
_super.call(this);
}
/**
* Schedules this action on its parent Scheduler for execution. May be passed
* some context object, `state`. May happen at some point in the future,
* according to the `delay` parameter, if specified.
* @param {T} [state] Some contextual data that the `work` function uses when
* called by the Scheduler.
* @param {number} [delay] Time to wait before executing the work, where the
* time unit is implicit and defined by the Scheduler.
* @return {void}
*/
Action.prototype.schedule = function (state, delay) {
if (delay === void 0) { delay = 0; }
return this;
};
return Action;
}(Subscription_1.Subscription));
exports.Action = Action;
//# sourceMappingURL=Action.js.map
/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var root_1 = __webpack_require__(16);
var Action_1 = __webpack_require__(322);
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var AsyncAction = (function (_super) {
__extends(AsyncAction, _super);
function AsyncAction(scheduler, work) {
_super.call(this, scheduler, work);
this.scheduler = scheduler;
this.work = work;
this.pending = false;
}
AsyncAction.prototype.schedule = function (state, delay) {
if (delay === void 0) { delay = 0; }
if (this.closed) {
return this;
}
// Always replace the current state with the new state.
this.state = state;
// Set the pending flag indicating that this action has been scheduled, or
// has recursively rescheduled itself.
this.pending = true;
var id = this.id;
var scheduler = this.scheduler;
//
// Important implementation note:
//
// Actions only execute once by default, unless rescheduled from within the
// scheduled callback. This allows us to implement single and repeat
// actions via the same code path, without adding API surface area, as well
// as mimic traditional recursion but across asynchronous boundaries.
//
// However, JS runtimes and timers distinguish between intervals achieved by
// serial `setTimeout` calls vs. a single `setInterval` call. An interval of
// serial `setTimeout` calls can be individually delayed, which delays
// scheduling the next `setTimeout`, and so on. `setInterval` attempts to
// guarantee the interval callback will be invoked more precisely to the
// interval period, regardless of load.
//
// Therefore, we use `setInterval` to schedule single and repeat actions.
// If the action reschedules itself with the same delay, the interval is not
// canceled. If the action doesn't reschedule, or reschedules with a
// different delay, the interval will be canceled after scheduled callback
// execution.
//
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, delay);
}
this.delay = delay;
// If this action has already an async Id, don't request a new one.
this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
return this;
};
AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
};
AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
// If this action is rescheduled with the same delay time, don't clear the interval id.
if (delay !== null && this.delay === delay && this.pending === false) {
return id;
}
// Otherwise, if the action's delay time is different from the current delay,
// or the action has been rescheduled before it's executed, clear the interval id
return root_1.root.clearInterval(id) && undefined || undefined;
};
/**
* Immediately executes this action and the `work` it contains.
* @return {any}
*/
AsyncAction.prototype.execute = function (state, delay) {
if (this.closed) {
return new Error('executing a cancelled action');
}
this.pending = false;
var error = this._execute(state, delay);
if (error) {
return error;
}
else if (this.pending === false && this.id != null) {
// Dequeue if the action didn't reschedule itself. Don't call
// unsubscribe(), because the action could reschedule later.
// For example:
// ```
// scheduler.schedule(function doWork(counter) {
// /* ... I'm a busy worker bee ... */
// var originalAction = this;
// /* wait 100ms before rescheduling the action */
// setTimeout(function () {
// originalAction.schedule(counter + 1);
// }, 100);
// }, 1000);
// ```
this.id = this.recycleAsyncId(this.scheduler, this.id, null);
}
};
AsyncAction.prototype._execute = function (state, delay) {
var errored = false;
var errorValue = undefined;
try {
this.work(state);
}
catch (e) {
errored = true;
errorValue = !!e && e || new Error(e);
}
if (errored) {
this.unsubscribe();
return errorValue;
}
};
AsyncAction.prototype._unsubscribe = function () {
var id = this.id;
var scheduler = this.scheduler;
var actions = scheduler.actions;
var index = actions.indexOf(this);
this.work = null;
this.delay = null;
this.state = null;
this.pending = false;
this.scheduler = null;
if (index !== -1) {
actions.splice(index, 1);
}
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, null);
}
};
return AsyncAction;
}(Action_1.Action));
exports.AsyncAction = AsyncAction;
//# sourceMappingURL=AsyncAction.js.map
/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Scheduler_1 = __webpack_require__(266);
var AsyncScheduler = (function (_super) {
__extends(AsyncScheduler, _super);
function AsyncScheduler() {
_super.apply(this, arguments);
this.actions = [];
/**
* A flag to indicate whether the Scheduler is currently executing a batch of
* queued actions.
* @type {boolean}
*/
this.active = false;
/**
* An internal ID used to track the latest asynchronous task such as those
* coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
* others.
* @type {any}
*/
this.scheduled = undefined;
}
AsyncScheduler.prototype.flush = function (action) {
var actions = this.actions;
if (this.active) {
actions.push(action);
return;
}
var error;
this.active = true;
do {
if (error = action.execute(action.state, action.delay)) {
break;
}
} while (action = actions.shift()); // exhaust the scheduler queue
this.active = false;
if (error) {
while (action = actions.shift()) {
action.unsubscribe();
}
throw error;
}
};
return AsyncScheduler;
}(Scheduler_1.Scheduler));
exports.AsyncScheduler = AsyncScheduler;
//# sourceMappingURL=AsyncScheduler.js.map
/***/ }),
/* 325 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* An error thrown when an element was queried at a certain index of an
* Observable, but no such index or position exists in that sequence.
*
* @see {@link elementAt}
* @see {@link take}
* @see {@link takeLast}
*
* @class ArgumentOutOfRangeError
*/
var ArgumentOutOfRangeError = (function (_super) {
__extends(ArgumentOutOfRangeError, _super);
function ArgumentOutOfRangeError() {
var err = _super.call(this, 'argument out of range');
this.name = err.name = 'ArgumentOutOfRangeError';
this.stack = err.stack;
this.message = err.message;
}
return ArgumentOutOfRangeError;
}(Error));
exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
//# sourceMappingURL=ArgumentOutOfRangeError.js.map
/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* An error thrown when one or more errors have occurred during the
* `unsubscribe` of a {@link Subscription}.
*/
var UnsubscriptionError = (function (_super) {
__extends(UnsubscriptionError, _super);
function UnsubscriptionError(errors) {
_super.call(this);
this.errors = errors;
var err = Error.call(this, errors ?
errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : '');
this.name = err.name = 'UnsubscriptionError';
this.stack = err.stack;
this.message = err.message;
}
return UnsubscriptionError;
}(Error));
exports.UnsubscriptionError = UnsubscriptionError;
//# sourceMappingURL=UnsubscriptionError.js.map
/***/ }),
/* 327 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Subscriber_1 = __webpack_require__(5);
var rxSubscriber_1 = __webpack_require__(81);
var Observer_1 = __webpack_require__(103);
function toSubscriber(nextOrObserver, error, complete) {
if (nextOrObserver) {
if (nextOrObserver instanceof Subscriber_1.Subscriber) {
return nextOrObserver;
}
if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
return nextOrObserver[rxSubscriber_1.rxSubscriber]();
}
}
if (!nextOrObserver && !error && !complete) {
return new Subscriber_1.Subscriber(Observer_1.empty);
}
return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
}
exports.toSubscriber = toSubscriber;
//# sourceMappingURL=toSubscriber.js.map
/***/ })
]);
//# sourceMappingURL=vendor.bundle.js.map